GithubHelp home page GithubHelp logo

nestjs-ottoman's Introduction

Description

A Couchbase module for Nestjs, built on top of the ODM ottoman 2.x

Supported Couchbase version

  • Server version 6.x, 7.x
  • Nodejs SDK 3.x

Usage

Installation

Yarn

yarn add nestjs-ottoman

NPM

npm install nestjs-ottoman --save

Integration

  1. Import CouchbaseModule in the root App module(or whatever other module that contains other modules), this provides initialized ottoman connection instance that is available to other modules by injection. Use CouchbaseModule.forRootAsync() if the module options depend on asynchronous processing. You can also bootstrap multiple Ottoman connections corresponding to different cluster/buckets in one CouchbaseModule.
import { Module } from '@nestjs/common';
import { CouchbaseModule } from 'nestjs-ottoman';
import configuration from './src/configuration';

@Module({
  imports: [
    ConfigModule.forRoot({
      load: [configuration],
    }),
    CouchbaseModule.forRootAsync([{ // or CouchbaseModule.forRoot with a static option
      imports: [ConfigModule],
      useFactory: async (configService: ConfigService) => {
        return configService.get('couchbase');
      },
      inject: [ConfigService],
    }, {
      connectionName: 'pet',
      ottomanConnectionOptions: {
        connectionString: 'couchbase://localhost:8091',
        bucketName: 'pet_bucket',
        username: 'Administrator',
        password: 'password',
      },
    }
    ]),
  ],
})
export class AppModule {}

The configuration file looks like,

export default () => ({
  couchbase: {
    connectionName: 'cat',
    ottomanConnectionOptions: {
      connectionString: 'couchbase://localhost:8091',
      bucketName: 'cat_bucket',
      username: 'Administrator',
      password: 'password',
    },
  }
});
  1. Define an Ottoman Model and schema, user CouchbaseModule.forFeature() to initialize and inject the Model object to other app modules.
import { Module } from '@nestjs/common';
import { CouchbaseModule } from 'nestjs-ottoman';
import { CatModelDefinition } from './cat.schema';
@Module({
  //'cat' has to match the "connectionName" in step 1
  imports: [CouchbaseModule.forFeature([CatModelDefinition], 'cat')], 
  
})
export class CatModule {}
  1. Inject initialized Model object to your service class. See the Ottoman documentation for Model API details.
import { Injectable } from '@nestjs/common';
import { Model, Ottoman } from 'ottoman';
import { InjectModel } from 'nestjs-ottoman';
import { CatModelDefinition } from './cat.schema';
@Injectable()
export class CatService {
  constructor(
    @InjectModel(CatModelDefinition.name) private catsModel: Model<any>
  ) {}

  async findById(name: string): Promise<any> {
    return this.catsModel.findById(name);
  }

  // other codes ...

}
  1. Optionally, you can also inject a global ottoman connection pools in case of you need to use the low level Couchbase SDK directly. You can get the specific connection by connectionName, then the bucket property on the connection is a reference to bucket class of Couchabse Nodejs SDK.
import { Injectable } from '@nestjs/common';
import { Model, Ottoman } from 'ottoman';
import { InjectConnections } from 'nestjs-ottoman';
@Injectable()
export class CatService {
  constructor(
    @InjectConnections() private connections: Map<String, Ottoman>,
  ) {}

  // a function using the map-reduce view query
  async findByBreed(breed: string): Promise<any> {
    const res = await this.connections
      .get('cat') // `connectionName` in step1,
      .bucket.viewQuery('_default_default', 'findByBreed', {
        key: breed,
      });
    return res.rows;
  }
}

Complete example code can be found in test folder.

Couchbase Indexes

According to the Ottoman Document, building the index can cause a significant performance impact, this Nestjs-Ottoman won't take care of index building, you have to have another script or application to handle the index initialization.

Design

Modeling

                                                           ╔══════════════════════════════════════╗
                                                           ║                                      ║
                                                           ║                  (scope:collection-1)║
                                                           ║  ┌───────────┐  ┌──────────┐         ║
                                                       ┌───╬─▶│  Model1   │  │ Schema1  │         ║
                                                       │   ║  └───────────┘  └──────────┘         ║
                                                       │   ║                                      ║
┌────────────────────┐     ┌─────────────────────┐     │   ║                                      ║
│       bucket       │     │                     │     │   ╚══════════════════════════════════════╝
│                    │     │  Ottoman instance1  │     │   ╔══════════════════════════════════════╗
│  (cluster:bucket)  │────▶│    (connection1)    │─────┤   ║                                      ║
│                    │     │                     │     │   ║                  (scope:collection-2)║
└────────────────────┘     └─────────────────────┘     │   ║   ┌──────────┐  ┌───────────┐        ║
                                                       └───╬─▶ │  Model2  │  │  Schema2  │        ║
                                                           ║   └──────────┘  └───────────┘        ║
                                                           ║                                      ║
                                                           ║                                      ║
                                                           ╚══════════════════════════════════════╝
                                                                                                   
                                                           ╔══════════════════════════════════════╗
                                                           ║                                      ║
                                                           ║                  (scope:collection-1)║
                                                           ║   ┌───────────┐  ┌──────────┐        ║
                                                        ┌──╬──▶│  Model3   │  │ Schema3  │        ║
 ┌─────────────────────┐    ┌─────────────────────┐     │  ║   └───────────┘  └──────────┘        ║
 │       bucket        │    │                     │     │  ║                                      ║
 │                     │    │  Ottoman instance2  │     │  ║                                      ║
 │  (cluster:bucket)   │───▶│    (connection2)    │─────┤  ║                                      ║
 │                     │    │                     │     │  ║    ┌──────────┐  ┌───────────┐       ║
 └─────────────────────┘    └─────────────────────┘     └──╬──▶ │  Model4  │  │  Schema4  │       ║
                                                           ║    └──────────┘  └───────────┘       ║
                                                           ║                                      ║
                                                           ╚══════════════════════════════════════╝
                                                                                   

Ottoman Models spawning

                                                ┌─────────────────────────────────────────┐       
┌────────────────────────────────────┐          │                                         │       
│Connection pool Provider            │          │                                         │       
│                                    │          │                                         │       
│             ┌────────────────┐     │          │                                         │       
│             │  connection1   │     │          │    ForFeature('model def', connName)    │       
│             └────────────────┘     │◀───use───│                                         │       
│             ┌────────────────┐     │          │                                         │       
│             │  connenction2  │     │          │                                         │       
│             └────────────────┘     │          │                                         │       
└────────────────────────────────────┘          │                                         │       
                                                └─────────────────────────────────────────┘       
                                                                     │                            
                                                                     │                            
                                               ┌─────────generate────┴──generate───────┐          
                                               │                                       │          
                                               ▼                                       ▼          
                                    ┌────────────────────┐                  ┌────────────────────┐
                                    │                    │                  │                    │
                                    │  Provider-Model2   │                  │  Provider-Model1   │
                                    │                    │                  │                    │
                                    │                    │                  │                    │
                                    │                    │                  │                    │
                                    └────────────────────┘                  └────────────────────┘

Development

Installation

$ yarn install

Test

Bootstrap the Couchbase servcie.

$ ./dockers/up.sh

Run the test code

$ yarn test

License

MIT licensed.

nestjs-ottoman's People

Contributors

xavierchow avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.