Skip to content

Commit

Permalink
v1.1.0
Browse files Browse the repository at this point in the history
  • Loading branch information
juanhapes committed May 19, 2020
2 parents 8e7c3cb + b867c19 commit ffdf237
Show file tree
Hide file tree
Showing 9 changed files with 382 additions and 111 deletions.
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,14 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).

## [Unreleased]
### Added
- `databaseSettings` parameter for `postSaveHook()` method

### Changed
- `Client` Model now set the new clients databaseKey from config

### Fixed
- `Client Create API` `postSaveHook()` client codes parameter

## [1.1.0] - 2020-05-19
### Removed
Expand Down
91 changes: 88 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@


## Introduction
This package includes all the generic functionality of the creation of a client at the services. It main purpose is to avoid code repetition.
This package includes all the generic functionality of the creation of a client at the services. It main purpose is to avoid code repetition.

## Installation
```sh
npm install @janiscommerce/client-creator
Expand All @@ -14,6 +15,31 @@ npm install @janiscommerce/client-creator

After installing this package you should create or update the following files:

### Service settings (.janiscommercerc)
You should configure the database config in your service, in order to get the correct DB config for new clients:

#### .janiscommercerc.json
```js
{
"database": {
"core": { // DB config where save new clients
"type": "mongodb",
"host": "core-host"
// ...
},
"newClients": { // DB config that the clients will use
"type": "mongodb",
"host": "clients-host"
// ...
}
},
"clients": {
"databaseKey": "newClients", // The new clients config databaseKey,
"table": "clients" // The clients table where create the clients ("clients" by default)
}
}
```

### ClientModel
At `./[MS_PATH]/models/client.js`

Expand Down Expand Up @@ -72,7 +98,6 @@ const { helper } = require('sls-helper'); // eslint-disable-line
const functions = require('./serverless/functions.json');
const { clientFunctions } = require('@janiscommerce/client-creator');


module.exports = helper({
hooks: [
// other hooks
Expand Down Expand Up @@ -109,4 +134,64 @@ Finally, create or update `./.nycrc` to avoid coverage leaks:
}
```

:warning: If exists any customization of the files, do not add the file to the .nyrcr and add the corresponding tests.
:warning: If exists any customization of the files, do not add the file to the .nyrcr and add the corresponding tests.

### Hooks
Both `APICreate` and `ListenerCreated` have a hook for post processing the client or clients created data.

#### APICreate

#### `postSaveHook(clientCodes, databaseSettings)`
Receives the clientCodes from the API and the databaseSettings for the created clients.

Parameters:
- clientCodes `string Array`: The client created codes .
- databaseSettings `Object`: The database settings of the created clients.

##### Example
```js
'use strict';
const { APICreate } = require('@janiscommerce/client-creator')

class ClientCreateAPI extends APICreate {

async postSaveHook(clientCodes, databaseSettings) {

await myPostSaveMethod(clientCodes, databaseSettings);

clientCodes.forEach(code => {
console.log(`Saved client ${code} with host: ${databaseSettings.host}`);
})
}
}

module.exports = ClientCreateAPI;
```

#### ListenerCreated

#### `postSaveHook(clientCode, databaseSettings)`
Receives the clientCode from the event and the databaseSettings for the created client.

Parameters:
- clientCode `string`: The client created code .
- databaseSettings `Object`: The database settings of the created client.

##### Example
```js
'use strict';
const { ServerlessHandler } = require('@janiscommerce/event-listener');
const { ListenerCreated } = require('@janiscommerce/client-creator');

class ClientCreateListener extends ListenerCreated {

async postSaveHook(clientCode, databaseSettings) {

await myPostSaveMethod(clientCode, databaseSettings);

console.log(`Saved client ${code} with host: ${databaseSettings.host}`);
}
}

module.exports.handler = (...args) => ServerlessHandler.handle(ClientCreateListener, ...args);
```
36 changes: 19 additions & 17 deletions lib/api-create.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,18 @@ const InstanceGetter = require('./helper/instance-getter');

const mongoDBIndexCreator = new MongoDBIndexCreator();


class ClientCreateAPI extends API {

get clientModel() {

if(!this._clientModel) {
const instanceGetter = this.session.getSessionInstance(InstanceGetter);
this._clientModel = instanceGetter.getModelInstance('client');
}

return this._clientModel;
}

async validate(data = this.data) {

if(data === null || typeof data !== 'object' || Array.isArray(data))
Expand All @@ -19,13 +28,9 @@ class ClientCreateAPI extends API {
throw new Error('Invalid data: Should have a clients property and must be an array.');
}

async process({ clients } = this.data) {
async process({ clients: clientCodes } = this.data) {

const instanceGetter = this.session.getSessionInstance(InstanceGetter);

const clientModel = instanceGetter.getModelInstance('client');

const databaseSettings = Settings.get('database')[clientModel.databaseKey];
const databaseSettings = Settings.get('database')[this.clientModel.databaseKey];

const clientDatabase = {
dbHost: databaseSettings.host
Expand All @@ -43,22 +48,19 @@ class ClientCreateAPI extends API {
if(databaseSettings.password)
clientDatabase.dbPassword = databaseSettings.password;


const clientsCodes = [];
const clientsToCreate = clients.map(client => {
clientsCodes.push(client.code);
const clientsToCreate = clientCodes.map(code => {
return {
code: client,
status: clientModel.constructor.statuses.active,
code,
status: this.clientModel.constructor.statuses.active,
...clientDatabase,
dbDatabase: `janis-${client}`
dbDatabase: `janis-${code}`
};
});


await clientModel.multiSave(clientsToCreate);
await this.clientModel.multiSave(clientsToCreate);
await mongoDBIndexCreator.executeForClientDatabases();
await this.postSaveHook(clientsCodes);

return this.postSaveHook(clientCodes, databaseSettings);
}

/**
Expand Down
20 changes: 13 additions & 7 deletions lib/listener-created.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,19 @@ class ClientCreatedListener extends EventListener {
return true;
}

async process(clientCode = this.eventId) {
get clientModel() {

if(!this._clientModel) {
const instanceGetter = this.session.getSessionInstance(InstanceGetter);
this._clientModel = instanceGetter.getModelInstance('client');
}

const instanceGetter = this.session.getSessionInstance(InstanceGetter);
return this._clientModel;
}

const clientModel = instanceGetter.getModelInstance('client');
async process(clientCode = this.eventId) {

const databaseSettings = Settings.get('database')[clientModel.databaseKey];
const databaseSettings = Settings.get('database')[this.clientModel.databaseKey];

const clientDatabase = {
dbHost: databaseSettings.host,
Expand All @@ -42,14 +48,14 @@ class ClientCreatedListener extends EventListener {
clientDatabase.dbPassword = databaseSettings.password;


await clientModel.save({
await this.clientModel.save({
code: clientCode,
status: clientModel.constructor.statuses.active,
status: this.clientModel.constructor.statuses.active,
...clientDatabase
});

await mongoDBIndexCreator.executeForClientCode(clientCode);
await this.postSaveHook(clientCode);
return this.postSaveHook(clientCode, databaseSettings);
}

/**
Expand Down
9 changes: 7 additions & 2 deletions lib/model-client.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,20 @@
'use strict';

const Model = require('@janiscommerce/model');
const Settings = require('@janiscommerce/settings');

class Client extends Model {

static get settings() {
return Settings.get('clients') || {};
}

get databaseKey() {
return 'newClients';
return this.constructor.settings.databaseKey || 'core';
}

static get table() {
return 'clients';
return this.settings.table || 'clients';
}

static get uniqueIndexes() {
Expand Down
5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,13 @@
"license": "ISC",
"homepage": "https://github.com/janis-commerce/client-creator.git#readme",
"devDependencies": {
"husky": "^2.4.1",
"eslint": "^5.16.0",
"eslint-config-airbnb-base": "^13.1.0",
"eslint-plugin-import": "^2.17.3",
"husky": "^2.4.1",
"mocha": "^5.2.0",
"nyc": "^13.1.0"
"nyc": "^13.1.0",
"sinon": "^9.0.2"
},
"files": [
"lib/"
Expand Down
Loading

0 comments on commit ffdf237

Please sign in to comment.