Skip to content

Commit

Permalink
Fixed postSaveHook and added databaseSettingsSource config
Browse files Browse the repository at this point in the history
  • Loading branch information
Nataniel López committed May 14, 2020
1 parent b8a682e commit 0d73fcc
Show file tree
Hide file tree
Showing 7 changed files with 379 additions and 64 deletions.
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,12 @@ 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
- `databaseSettingsSource` getter to specify other settings source for client DB config

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

## [1.0.4] - 2020-05-04
### Fixed
Expand Down
117 changes: 116 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -109,4 +109,119 @@ 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.

### Getters
Both `APICreate` and `ListenerCreated` have a getter for customize the client creation settings.

#### `databaseSettingsSource` (*`instance getter`*): Is the database config source key that will be getted from your MS database config. Default: `clientModel.databaseKey`.

##### Example

##### .janiscommercerc
```js
{
"database":{
"newClients": {
type: 'mongodb',
host: 'core-host'
// ...
},
otherDb: {
host: 'http://clients-host:8983',
type: 'solr'
}
}
}
```

##### `./[MS_PATH]/api/client/post.js`
```js
'use strict';
const { APICreate } = require('@janiscommerce/client-creator')

class ClientCreateAPI extends APICreate {

get databaseSettingsSource() {
return 'otherDb';
}
}

module.exports = ClientCreateAPI;
```

##### `./[MS_PATH]/event-listeners/id/client/created.js`
```js
'use strict';
const { ServerlessHandler } = require('@janiscommerce/event-listener');
const { ListenerCreated } = require('@janiscommerce/client-creator');

class ClientCreateListener extends ListenerCreated {

get databaseSettingsSource() {
return 'otherDb';
}
}

module.exports.handler = (...args) => ServerlessHandler.handle(ClientCreateListener, ...args);
```

### 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);
```
40 changes: 23 additions & 17 deletions lib/api-create.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,22 @@ 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;
}

get databaseSettingsSource() {
return this.clientModel.databaseKey;
}

async validate(data = this.data) {

if(data === null || typeof data !== 'object' || Array.isArray(data))
Expand All @@ -19,13 +32,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) {

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

const clientModel = instanceGetter.getModelInstance('client');
async process({ clients: clientCodes } = this.data) {

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

const clientDatabase = {
dbHost: databaseSettings.host
Expand All @@ -43,22 +52,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
24 changes: 17 additions & 7 deletions lib/listener-created.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,23 @@ 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');
}

return this._clientModel;
}

const instanceGetter = this.session.getSessionInstance(InstanceGetter);
get databaseSettingsSource() {
return this.clientModel.databaseKey;
}

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

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

const clientDatabase = {
dbHost: databaseSettings.host,
Expand All @@ -42,14 +52,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
2 changes: 1 addition & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading

0 comments on commit 0d73fcc

Please sign in to comment.