npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

typesense-nestjs

v2.0.3

Published

Typesence module for NestJS and sync data from monoDB

Downloads

133

Readme

About Typesense

Typesense is an open-source, typo-tolerant search engine optimized for instant (typically sub-50ms) search-as-you-type experiences and developer productivity.

If you've heard about ElasticSearch or Algolia, a good way to think about Typesense is that it is:

  • An open source alternative to Algolia, with some key quirks solved and
  • An easier-to-use batteries-included alternative to ElasticSearch

Read more about Typesense at here

Main Feature

| Name | Supported versions | |--------------------------------------|--------------------| | Register typesense global | All versions | | Register schema for specified module | All versions | | Auto migrate schemas | All versions | | Auto sync data from MongoDB | All versions | | Import sync module | v2.0.0 or later | | Define and inject Typesense Schema | v2.0.0 or later |

Install Typesense and MongoDB:

Please follow this guide to install and setup necessary services

Quick start:

Add necessary dependencies

yarn add mongoose @nestjs/mongoose typesense

Add typesense-nestjs:

yarn add typesense-nestjs

Register and config Typesense at app.module.ts

import { Module } from '@nestjs/common';
import { TypesenseNestModule } from 'typesense-nestjs';

@Module({
  imports: [
    ...
    TypesenseNestModule.forRootSync({
      useFactory: () => ({
        nodes: [
          {
            host: 'localhost',
            port: 8108,
            protocol: 'http',
          },
        ],
        apiKey: 'your typesense api key',
        logLevel: 'trace',
        retryIntervalSeconds: 2,
        timeoutSeconds: 4,
      }),
    }),
  ],
})
export class AppModule {}

Define new Typesense Schema

Please create a new schema file. Here's how you can create a new schema file named product-search.schema.ts in product directory

// product/product-search.schema.ts

import { Prop, TypesenseSchema, TypesenseSchemaFactory } from 'typesense-nestjs';

@TypesenseSchema({ name: 'products' })
export class ProductSearch {
  @Prop()
  id: string;

  @Prop()
  name: string;

  @Prop()
  category: string;

  @Prop()
  subCategory: string;

  @Prop({ index: false })
  image: string;

  @Prop({ index: false })
  link: string;

  @Prop({ type: 'float' })
  ratings: number;

  @Prop({ type: 'int32' })
  noOfRatings: number;

  @Prop({ type: 'float' })
  discountPrice: number;

  @Prop({ type: 'float' })
  actualPrice: number;
}

export const ProductSearchSchema = TypesenseSchemaFactory.createForClass(ProductSearch);

See Typesense Schema Parameters for all available options for schema, and Prop Field Parameters for all available options for prop.

Import schema to Typesense

// product/product.module.ts

import { TypesenseNestModule } from 'typesense-nestjs';
import { Module } from '@nestjs/common';

import { ProductSearch, ProductSearchSchema } from './schemas/product-search.schema';

@Module({
  imports: [
    ...
    TypesenseNestModule.forFeature({
      name: ProductSearch.name,
      schema: ProductSearchSchema,
    }),
  ],
  ...
})
...

How to sync data from MongoDB

// product/product.service.ts

import { Injectable, OnApplicationShutdown } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { ChangeStream, ChangeStreamDocument, Model } from 'mongoose';
import { InjectTypesenseModel, TypesenseSearchModel } from 'typesense-nestjs';

import { Product } from './product/schemas/product.schema';
import { ProductSearch } from './product/schemas/product-search.schema';

@Injectable()
export class ProductService implements OnApplicationShutdown {
  protected readonly _ModelChangeStream: ChangeStream<Product, ChangeStreamDocument<Product>>;

  constructor(
    @InjectModel(Product.name) private readonly _ProductModel: Model<Product>,
    @InjectTypesenseModel(ProductSearch.name)
    private readonly _ProductSearchCollection: TypesenseSearchModel<ProductSearch>,
  ) {
    this._ProductModel.watch().on('change', async (e) => {
      await this._ProductSearchCollection.syncData(e);
    });
  }

  async onApplicationShutdown() {
    if (this._ModelChangeStream) {
      await this._ModelChangeStream.close();
    }
  }
}

The code snippet above is essential for monitoring changes in the MongoDB data stream and promptly updating the data in Typesense.

Notice: Please remember to enable app shutdown hooks and close the change stream when shutting down the app.

To enable shutdown hooks. Please use the code below:

// main.ts
  ...
  app.enableShutdownHooks();

  await app.listen(3000);
  ...

How to use?

The property below was provided for us some methods such as: seach, create, update documents,... Please see this guide to use it!.

this._ProductSearchCollection.documents

The code snippet below is simple search:

this._ProductSearchCollection.documents.search({
    q: 'text query',
    per_page: 10,
    page: 1,
    query_by: 'name,category,subCategory',
});