0.8.25 • Published 5 months ago

moleculer-db v0.8.25

Weekly downloads
11,469
License
MIT
Repository
github
Last release
5 months ago

Moleculer logo

moleculer-db NPM version

Moleculer service to store entities in database.

Features

  • default CRUD actions
  • cached actions
  • pagination support
  • pluggable adapter (NeDB is the default memory adapter for testing & prototyping)
  • official adapters for MongoDB, PostgreSQL, SQLite, MySQL, MSSQL.
  • fields filtering
  • populating
  • encode/decode IDs
  • entity lifecycle events for notifications

Install

$ npm install moleculer-db --save

Usage

"use strict";

const { ServiceBroker } = require("moleculer");
const DbService = require("moleculer-db");

const broker = new ServiceBroker();

// Create a DB service for `user` entities
broker.createService({
    name: "users",
    mixins: [DbService],

    settings: {
        fields: ["_id", "username", "name"]
    },

    afterConnected() {
        // Seed the DB with ˙this.create`
    }
});

broker.start()

// Create a new user
.then(() => broker.call("users.create", {
    username: "john",
    name: "John Doe",
    status: 1
}))

// Get all users
.then(() => broker.call("users.find").then(console.log));

// List users with pagination
.then(() => broker.call("users.list", { page: 2, pageSize: 10 }).then(console.log));

// Get a user
.then(() => broker.call("users.get", { id: 2 }).then(console.log));

// Update a user
.then(() => broker.call("users.update", { id: 2, name: "Jane Doe" }).then(console.log));

// Delete a user
.then(() => broker.call("users.remove", { id: 2 }).then(console.log));

Settings

PropertyTypeDefaultDescription
idFieldStringrequiredName of ID field.
fieldsArray.<String>nullField filtering list. It must be an Array. If the value is null or undefined doesn't filter the fields of entities.
excludeFieldsArray.<String>nullExclude fields from list. It must be an Array.
populatesArraynullSchema for population. Read more.
pageSizeNumberrequiredDefault page size in list action.
maxPageSizeNumberrequiredMaximum page size in list action.
maxLimitNumberrequiredMaximum value of limit in find action. Default: -1 (no limit)
entityValidatorObject, functionnullValidator schema or a function to validate the incoming entity in create & 'insert' actions.

Note: idField does not work with Sequelize adapter as you can freely set your own ID while creating the model.

Actions

find Cached action

Find entities by query.

Parameters

PropertyTypeDefaultDescription
populateString, Array.<String>requiredPopulated fields.
fieldsString, Array.<String>requiredFields filter.
limitNumber-Max count of rows.
offsetNumber-Count of skipped rows.
sortString-Sorted fields.
searchString-Search text.
searchFieldsString, Array.<String>requiredFields for searching.
queryObject-Query object. Passes to adapter.

Results

Type: Array.<Object>

List of found entities.

count Cached action

Get count of entities by query.

Parameters

PropertyTypeDefaultDescription
searchString-Search text.
searchFieldsString, Array.<String>requiredFields list for searching.
queryObject-Query object. Passes to adapter.

Results

Type: Number

Count of found entities.

list Cached action

List entities by filters and pagination results.

Parameters

PropertyTypeDefaultDescription
populateString, Array.<String>requiredPopulated fields.
fieldsString, Array.<String>requiredFields filter.
pageNumber-Page number.
pageSizeNumber-Size of a page.
sortString-Sorted fields.
searchString-Search text.
searchFieldsString, Array.<String>requiredFields for searching.
queryObject-Query object. Passes to adapter.

Results

Type: Object

List of found entities and count with pagination info.

create

Create a new entity.

Parameters

PropertyTypeDefaultDescription
paramsObjectrequiredEntity to save.

Results

Type: Object

Saved entity.

insert

Create many new entities.

Parameters

PropertyTypeDefaultDescription
entityObject-Entity to save.
entitiesArray.<Object>-Entities to save.

Results

Type: Object, Array.<Object>

Saved entity(ies).

get Cached action

Get entity by ID.

Parameters

PropertyTypeDefaultDescription
idany, Array.<any>requiredID(s) of entity.
populateString, Array.<String>requiredField list for populate.
fieldsString, Array.<String>requiredFields filter.
mappingBoolean-Convert the returned Array to Object where the key is the value of id.

Results

Type: Object, Array.<Object>

Found entity(ies).

update

Update an entity by ID.

After update, clear the cache & call lifecycle events.

Parameters

PropertyTypeDefaultDescription
idanyrequiredID of entity.

Results

Type: Object

Updated entity.

remove

Remove an entity by ID.

Parameters

PropertyTypeDefaultDescription
idanyrequiredID of entity.

Results

Type: Number

Count of removed entities.

Methods

sanitizeParams

Sanitize context parameters at find action.

Parameters

PropertyTypeDefaultDescription
ctxContextrequired
paramsObjectrequired

Results

Type: Object

getById

Get entity(ies) by ID(s).

Parameters

PropertyTypeDefaultDescription
idany, Array.<any>requiredID or IDs.
decodingBoolean-Need to decode IDs.

Results

Type: Object, Array.<Object>

Found entity(ies).

entityChanged

Clear the cache & call entity lifecycle events

Parameters

PropertyTypeDefaultDescription
typeStringrequired
jsonObject, Array.<Object>, Numberrequired
ctxContextrequired

Results

Type: Promise

clearCache

Clear cached entities

Parameters

PropertyTypeDefaultDescription

No input parameters.

Results

Type: Promise

transformDocuments

Transform the fetched documents

Parameters

PropertyTypeDefaultDescription
ctxContextrequired
paramsObjectrequired
docsArray, Objectrequired

Results

Type: Array, Object

validateEntity

Validate an entity by validator.

Parameters

PropertyTypeDefaultDescription
entityObjectrequired

Results

Type: Promise

encodeID

Encode ID of entity.

Parameters

PropertyTypeDefaultDescription
idanyrequired

Results

Type: any

decodeID

Decode ID of entity.

Parameters

PropertyTypeDefaultDescription
idanyrequired

Results

Type: any

_find

Find entities by query.

Parameters

PropertyTypeDefaultDescription
ctxContextrequiredContext instance.
paramsObject-Parameters.

Results

Type: Array.<Object>

List of found entities.

_count

Get count of entities by query.

Parameters

PropertyTypeDefaultDescription
ctxContextrequiredContext instance.
paramsObject-Parameters.

Results

Type: Number

Count of found entities.

_list

List entities by filters and pagination results.

Parameters

PropertyTypeDefaultDescription
ctxContextrequiredContext instance.
paramsObject-Parameters.

Results

Type: Object

List of found entities and count.

_create

Create a new entity.

Parameters

PropertyTypeDefaultDescription
ctxContextrequiredContext instance.
paramsObject-Parameters.

Results

Type: Object

Saved entity.

_insert

Create many new entities.

Parameters

PropertyTypeDefaultDescription
ctxContextrequiredContext instance.
paramsObject-Parameters.

Results

Type: Object, Array.<Object>

Saved entity(ies).

_get

Get entity by ID.

Parameters

PropertyTypeDefaultDescription
ctxContextrequiredContext instance.
paramsObject-Parameters.

Results

Type: Object, Array.<Object>

Found entity(ies).

_update

Update an entity by ID.

After update, clear the cache & call lifecycle events.

Parameters

PropertyTypeDefaultDescription
ctxContextrequiredContext instance.
paramsObject-Parameters.

Results

Type: Object

Updated entity.

_remove

Remove an entity by ID.

Parameters

PropertyTypeDefaultDescription
ctxContextrequiredContext instance.
paramsObject-Parameters.

Populating

The service supports to populate fields from other services. E.g.: if you have an author field in post entity, you can populate it with users service by ID of author. If the field is an Array of IDs, it will populate all entities via only one request.

Example of populate schema

broker.createService({
    name: "posts",
    mixins: [DbService],
    settings: {
        populates: {
            // Shorthand populate rule. Resolve the `voters` values with `users.get` action.
            "voters": "users.get",

            // Define the params of action call. It will receive only with username & full name of author.
            "author": {
                action: "users.get",
                params: {
                    fields: "username fullName"
                }
            },

            // Custom populator handler function
            "rate"(ids, docs, rule, ctx) {
                return Promise.resolve(...);
            }
        }
    }
});

// List posts with populated authors
broker.call("posts.find", { populate: ["author"]}).then(console.log);

The populate parameter is available in find, list and get actions.

Lifecycle entity events

There are 3 lifecycle entity events which are called when entities are manipulated.

broker.createService({
    name: "posts",
    mixins: [DbService],
    settings: {},

    afterConnected() {
        this.logger.info("Connected successfully");
    },

    entityCreated(json, ctx) {
        this.logger.info("New entity created!");
    },

    entityUpdated(json, ctx) {
        // You can also access to Context
        this.logger.info(`Entity updated by '${ctx.meta.user.name}' user!`);
    },

    entityRemoved(json, ctx) {
        this.logger.info("Entity removed", json);
    },    
});

Please note! If you manipulate multiple entities (updateMany, removeMany), the json parameter will be a Number instead of entities!

Extend with custom actions

Naturally you can extend this service with your custom actions.

const DbService = require("moleculer-db");

module.exports = {
    name: "posts",
    mixins: [DbService],

    settings: {
        fields: ["_id", "title", "content", "votes"]
    },

    actions: {
        // Increment `votes` field by post ID
        vote(ctx) {
            return this.adapter.updateById(ctx.params.id, { $inc: { votes: 1 } });
        },

        // List posts of an author
        byAuthors(ctx) {
            return this.find({
                query: {
                    author: ctx.params.authorID
                },
                limit: ctx.params.limit || 10,
                sort: "-createdAt"
            });
        }
    }
}

Remove default actions

According to moleculer documentation you can disable an action when override it with false

const DbService = require("moleculer-db");

module.exports = {
    name: "posts",
    mixins: [DbService],

    actions: {
        // Disable find default action
        find: false
    }
}

Test

$ npm test

In development with watching

$ npm run ci

License

The project is available under the MIT license.

Contact

Copyright (c) 2016-2022 MoleculerJS

@moleculerjs @MoleculerJS

0.8.25

5 months ago

0.8.24

9 months ago

0.8.23

1 year ago

0.8.22

1 year ago

0.8.21

1 year ago

0.8.20

1 year ago

0.8.19

2 years ago

0.8.18

2 years ago

0.8.17

2 years ago

0.8.16

3 years ago

0.8.15

3 years ago

0.8.14

3 years ago

0.8.13

3 years ago

0.8.12

3 years ago

0.8.11

3 years ago

0.8.10

4 years ago

0.8.9

4 years ago

0.8.8

4 years ago

0.8.7

4 years ago

0.8.6

4 years ago

0.8.5

4 years ago

0.8.4

4 years ago

0.8.3

4 years ago

0.8.2

5 years ago

0.8.1

5 years ago

0.8.0

5 years ago

0.7.9

5 years ago

0.7.8

5 years ago

0.7.7

5 years ago

0.7.6

6 years ago

0.7.5

6 years ago

0.7.3

6 years ago

0.7.2

6 years ago

0.7.1

6 years ago

0.7.0

6 years ago

0.7.0-beta3

6 years ago

0.7.0-beta2

6 years ago

0.7.0-beta1

6 years ago

0.6.3

6 years ago

0.6.2

6 years ago

0.6.1

6 years ago

0.6.0

7 years ago

0.5.2

7 years ago

0.5.1

7 years ago

0.5.0

7 years ago

0.4.5

7 years ago

0.4.4

7 years ago

0.4.3

7 years ago

0.4.2

7 years ago

0.4.1

7 years ago

0.4.0

7 years ago

0.3.3

7 years ago

0.3.2

7 years ago

0.3.1

7 years ago

0.3.0

7 years ago

0.2.0

7 years ago

0.1.3

7 years ago

0.1.2

7 years ago

0.1.1

7 years ago

0.1.0

7 years ago