0.0.5 • Published 4 years ago

moleculer-db-adapter-typeorm-mongo v0.0.5

Weekly downloads
3
License
MIT
Repository
github
Last release
4 years ago

Moleculer logo

moleculer-db-adapter-typeorm-mongo NPM version

MongoDB adapter for Moleculer DB service with typeorm. Still a work in progress but stable.

Essentially a clone and modification of the great work on adaptor for Sequelize by the author of the project and dkuida.

it covers only the basics - but when you need more than basics just use the exposed

service.adapter.repository;

Features

  • Standard and multi-tenancy database connecitons
  • Create additional named typeorm connections in a service
  • List databases from a connection

Install

$ npm install moleculer-db-adapter-typeorm-mongo --save

Usage

/**
 * TypeORM db connection
 */
adapter: new TypeOrmDbAdapter({
    database: serviceDB,
    name: serviceName,
    // eslint-disable-next-line @typescript-eslint/ban-ts-ignore
    // @ts-ignore
    type: 'mongodb',
    host: 'localhost',
    port: 27017,
    entities: [serviceEntity],
    synchronize: true,
    useNewUrlParser: true,
    useUnifiedTopology: true,
}),

/**
 * TypeORM db model
 */
model: Entity,

/**
 * Service db connection mode
 * Either 'mt' for multitenant or 'stanard' for standard connection
 * string is case insensative.
 */
mode: 'standard',

Todo

  • gridfs integration for file / image storage in MongoDB

Test

$ npm test

Settings

PropertyTypeDefaultDescription

No settings.

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

Actions

Methods

find

Entity find

Parameters

PropertyTypeDefaultDescription
filtersObjectrequiredFilters object to apply

Examples

todo example

findOne

Entity fineone

Parameters

PropertyTypeDefaultDescription
queryObjectrequiredQuery object

Examples

todo example

findById

Entity find by id

Parameters

PropertyTypeDefaultDescription
idStringrequiredid of document

Examples

todo example

findByIds

Entity find by array of ids

Parameters

PropertyTypeDefaultDescription
idListArray.<(Object|String)>requiredlist of ids

Examples

todo example

count

Entity count

Parameters

PropertyTypeDefaultDescription
filtersObjectrequiredObject of filters to apply

Examples

todo example

insert

Entity insert

Parameters

PropertyTypeDefaultDescription
entityObjectrequireddocuemnt to save

Examples

todo example

create

Entity create

Parameters

PropertyTypeDefaultDescription
entityObjectrequireddocument to create

Examples

todo example

insertMany

Entity insert array of objects

Parameters

PropertyTypeDefaultDescription
entitiesArray.<Object>requiredArray of entities

Examples

todo example

updateMany

Entity update many

Parameters

PropertyTypeDefaultDescription
wherePromiserequiredPromise Object filter
updatePromiserequiredPromise Object update deep partial

Examples

todo example

updateById

Entity update by id

Parameters

PropertyTypeDefaultDescription
idStringrequiredid of document
updateObjectrequiredupdate object using deep partial

Examples

todo example

removeMany

Entity remove many

Parameters

PropertyTypeDefaultDescription
wherePromiserequiredpromise object filter

Examples

todo example

removeById

Entity remove by id

Parameters

PropertyTypeDefaultDescription
idStringrequiredid of document

Examples

todo example

connect

Conect to database

Parameters

PropertyTypeDefaultDescription
modeStringrequiredmode of adapter, either mt or standard
optionsObjectrequiredconnection options
cbObjectrequiredcallback with connection in mt mode

Results

Type: Connection, Repository, ConnectionManager

returns Connection, repository and connection manager

Examples

this.connect(); // connects to default db connection oof service
// new connection object
const newConnection = {
    database: 'products',
    type: String(process.env.DBENGINE),
    username: process.env.MONGOUSERNAME,
    password: process.env.MONGOPASSWORD,
    host: process.env.DBHOST,
    port: Number(process.env.DBPORT),
    authSource: process.env.AUTHSOURCE,
    appname: 'Cameo:service:testapiMT:Products',
    entities: [Products],
    synchronize: process.env.SYNCHRONIZE,
    useNewUrlParser: process.env.USENEWURLPARSER,
    useUnifiedTopology: process.env.USENEWURLPARSER,
};
const productsConnection = await new this.Promise(
  async (resolve, reject) => {
    // pass connection type, connection object and callback to retrieve the new connection object already connected
    await this.connect('mt', newConnection, (conn) => {
      if (!conn) {
        return reject("can't create connection");
      }
         // set new connection object to outside variable for use
         return resolve(conn);
    });
  }
);
// use new connection to query database
await productsConnection.connection.connect();
console.log(await productsConnection.connection.getMongoRepository(Products).find());
// close connection when done
await productsConnection.connection.close();
// use manager (Connection manager) to get all the available connections
console.log(productsConnection.manager);
// get connection you want to use
const connection = productsConnection.manager.get('products')
console.log(connection);
// opens connection
connection.connect();
{...}
// closes connection
connection.close();

disconnect

Disconnect from database

Parameters

PropertyTypeDefaultDescription

No input parameters.

Examples

this.disconnect(); // disconnects default service connection

createCursor

Create cursor

Parameters

PropertyTypeDefaultDescription
paramsObjectrequired
isCountingBooleanfalse

Examples

todo example

addDBUser

Add user to database

Parameters

PropertyTypeDefaultDescription
objanyrequiredConnection object
obj.urlStringrequiredDatabase url
obj.connectionOptsObjectrequiredDatabase connection options
obj.[key:anyrequiredstring] - Additional Key pair paramaters
userOptsanyrequiredUser object
userOpts.usernameStringrequiredUser name of user to be added
userOpts.passwordStringrequiredPassword of user to be added
userOpts.optionsObjectrequiredAdditional options to be passed to add user

Examples

todo example

command

Run database command

Parameters

PropertyTypeDefaultDescription
urlStringrequiredMongodb url
connectionOptsObjectrequiredMongodb connection options
commandObjectrequiredCommand object to send
optionsObjectrequiredAdditional options to add

Examples

todo example

createDB

Create Database

Parameters

PropertyTypeDefaultDescription
objanyrequiredConnection object
obj.urlStringrequiredMongo db url
obj.connectionOptsObjectrequiredMongo connection options
obj.databaseNameStringrequiredMongo db name
userOptsanyrequiredUser object (optional)
userOpts.usernameStringrequiredUser name
userOpts.PasswordStringrequiredUser Password
userOpts.optionsObjectrequiredUser options

Examples

await this.adapter.createDB(
    {
        url: `${process.env.URL}${tenantDB}?authSource=${process.env.AUTHSOURCE}`,
        connectionOpts: {
        useNewUrlParser: Boolean(process.env.USENEWURLPARSER),
        useUnifiedTopology: Boolean(process.env.USENEWURLPARSER),
    },
    databaseName: tenantDB,
    },
    {
        DBUser: ctx.params.db_username,
        DBPassword: ctx.params.db_password,
        options: { roles: ['dbOwner'] },
    },
);

listDataBases

List Databases on server

Parameters

PropertyTypeDefaultDescription
urlanyrequiredMongodb url wihtout database
optsanyrequiredMongodb connection options

Examples

console.log(
   await this.adapter
     .listDataBases(
       `${process.env.URL}?authSource=${process.env.AUTHSOURCE}`,
       {
           useNewUrlParser: Boolean(process.env.USENEWURLPARSER),
           useUnifiedTopology: Boolean(process.env.USENEWURLPARSER),
       },
   )
);

removeUser

Remove user from db

Parameters

PropertyTypeDefaultDescription
objanyrequiredDatabase connection object
userOptsanyrequiredUser object if user to be removed

Examples

todo example

updateDBUser

Update DB User

Parameters

PropertyTypeDefaultDescription
objanyrequiredConnection object
obj.urlStringrequiredMongo db url
obj.connectionOptsObjectrequiredMongo connection options
userOptsanyrequiredUser object
userOpts.usernameStringrequiredUser name
userOpts.PasswordStringrequiredUser Password
userOpts.optionsObjectrequiredUser options (roles)

Examples

todo example

License

The project is available under the MIT license.

Contact

Copyright (c) 2020 Karnith