Skip to content

ltv/moleculer-db-knex

Repository files navigation

Moleculer KnexDB Mixin

This package use for creating mixin for each service which can support

CircleCI Coverage Status License: MIT npm version

Usage

yarn add moleculer-db-knex
const connection: ConnectionConfig = {
  host: process.env.DB_HOST,
  database: process.env.DB_NAME,
  user: process.env.DB_USER,
  password: process.env.DB_PASS
};

const configs: Config = {
  client: 'postgresql',
  connection,
  pool: {
    min: 2,
    max: 10
  }
};

broker.createService({
  name: 'public',
  mixins: [
    KnexDbMixin({
      schema: 'adm',
      table: 'PubPost',
      knex: {
        configs
      }
    })
  ]
});
  • This mixin will create actions for service:
find: {
        params: {
          where: {
            type: 'object',
            optional: true
          }
        },
        cache: {
          keys: ['where']
        },
        handler(ctx: Context) {
        }
      },

      findById: {
        params: {
          [idField]: {
            type: 'any'
          }
        },
        cache: {
          keys: [idField]
        },
        handler(ctx: Context) {
        }
      },

      insert: {
        params: {
          entity: {
            type: 'any'
          }
        },
        handler(ctx: Context) {
          const { entity } = ctx.params;
          return this.insert(entity).then(res =>
            this.entityChanged('inserted', res, ctx).then(() => res)
          );
        }
      },

      updateById: {
        params: {
          [idField]: {
            type: 'any'
          },
          entity: {
            type: 'any'
          }
        },
        handler(ctx: Context) {
        }
      },

      deleteById: {
        params: {
          [idField]: {
            type: 'any'
          }
        },
        handler(ctx: Context) {
        }
      }
  • Service methods available:
/**
 * Clear the cache & call entity lifecycle events
 *
 * @param {String} type
 * @param {Object|Array|Number} json
 * @param {Context} ctx
 * @returns {Promise}
 */
entityChanged(type, json, ctx) {},

/**
 * Clear cached entities
 *
 * @methods
 * @returns {Promise}
 */
clearCache() {},

db(options?: { schema?: string; table: string }): QueryBuilder {},

find(opts?: { field: string; value: any; operator: string }) {},


insert(entity: any, returning?: string | string[]) {},


update(opts: {
  field: string;
  value: any;
  entity: any;
  returning?: string | string[];
}) {},


delete(opts: {
  field: string;
  value: any;
  returning?: string | string[];
}) {},

clean() {}
```

## Test

Before testing, please provision env with docker

```bash
yarn provision:dev
```

And then

```bash
yarn test:unit
```

Releases

No releases published

Packages

No packages published