1.0.0 • Published 4 years ago

@irieimperator/nest-couch v1.0.0

Weekly downloads
23
License
MIT
Repository
-
Last release
4 years ago

This module acts as a wrapper around nano providing a convenient "NestJS style" approach for using CouchDB. nano is Apaches official NodeJS library with TypeScript support.

Installation

npm i @irieimperator/nest-couch

Configuration

Options

Since it is a wrapper, you can use all options provided in nano. To establish a connection, you need at least:

parametertyperequireddescription
nano.urlstringtrueurl to connect to CouchDB, ex. https://USER:PASSWORD@HOST:PORT

In addition, nest-couch accepts additional parameters:

parametertyperequireddescription
defaultBucketstringfalsename of the default bucket you want to use
bucketsstring[]falsenames of buckets you want to use
logging.level'OFF' or 'INFO'falsecontrols level of logging

Import

This module can be imported and configured both synchronously and asynchronously.

synchron

NestCouchModule.register({
      nano: {
        url: 'https://USER:PASSWORD@HOST:PORT'
      },
      defaultBucket: 'cats',
      buckets: ['dogs', 'beavers', 'chinchillas'],
      logging: {
        level: 'INFO'
      }
})

asynchron

NestCouchModule.registerAsync({
  inject: [ConfigService],
  useFactory: (configService: ConfigService) => {
    return {
      nano: {
        url: configService.get<string>('DB_URL')
      },
      defaultBucket: configService.get<string>('DB_DEFAULT_BUCKET'),
      buckets: configService.get<string>('DB_BUCKETS').split(','),
      logging: {
        level: configService.get<'OFF' | 'INFO'>('DB_LOG_LEVEL')
      }
    };
  }
})

Usage

Depending on the configuration you have access to the following:

injected propertytypeexistsdescription
NEST_COUCH_CONNECTIONnano connection instancealways/
NEST_COUCH_DEFAULT_BUCKETnano.db.use(defaultBucket)if specified/
NEST_COUCH_BUCKETSmultiple nano.db.use(bucket)if specifiedreturns an object holding a nano.db.use(bucket) for each specified bucket, with the bucket name as key

You can use nest-couch in a service like that:

@Injectable()
export class AppService {
    constructor(
        @Inject(NEST_COUCH_CONNECTION) private readonly connection,
        @Inject(NEST_COUCH_DEFAULT_BUCKET) private readonly bucket,
        @Inject(NEST_COUCH_BUCKETS) private readonly buckets
    ) {}
    
    // use connection - create new bucket
    async createBucket(bucket: string) {
      await this.connection.db.create(bucket);
    }

    // use defaultBucket - list all objects
    async createBucket() {
      await this.bucket.list();
    }
    
    // use one of the other buckets - insert object
    async createBucket(bucket: string, object: MySpecialObject) {
      await this.buckets[bucket].insert(object);
    }
}

Thanks

The basic structure of this module was created with nestjsplus' dynamic module generator - thanks for saving the effort, works like a charm!