README
Thanos
Shawee express API bootstrap as module.
This module will contemple all base of shawee api's cofiguration, all shawee apis must be this configuration and patterns.
Why use Thanos?
It help us to have a ubiquitous language and a api development pattern. This module have all express apis middlweares, configurations and a ping route.
Getting Started
These instructions will get you how to install it and use on your shawee projects.
Prerequisites
- "node >= 8.11.1"
- "npm >= 6.4.0"
Installing
First install the package on your project.
npm install @shawee/thanos
Setup your api
After you have intalled the package @shawee/thanos
, require it at your index.js
const thanos = require('@shawee/thanos')
or
const { factory } = require('@shawee/thanos')
The thanos
constant or the factory
constant is a function that receive a callback function.
The factory/thanos
function return a express instance app, inside this function have all the express configuration like middlewares, ping route, log format... The callback function is like an configuration extension to express package, it's contain your own middlewares and routes.
This callback function is called at middle of the middlewares:
[ Inside the @shawee/thanos ]
[...]
const app = express()
app.use(middlewares.morgan.factory(config.morgan))
app.use(middlewares.parsers.urlencoded.factory())
app.use(middlewares.parsers.json.factory())
app.use(middlewares.helmet.factory())
app.get('/ping', routes.ping.factory(config, environment))
// Your callback function here
fn(app, config, environment, logger)
app.use('*', middlewares.routes.unmatched.factory())
app.use(middlewares.validation.errors.factory())
app.use(middlewares.struct.errors.factory())
app.use(middlewares.stderr.factory(logger))
app.use(middlewares.normalizer.factory())
app.use(middlewares.renderer.factory())
[...]
So, after required the @shawee/thanos
call the function factory and set the callback parameter. This callback parameter receive a express instance, config object, environment and logger object.
So your index.js is:
'use strict'
const thanos = require('@shawee/thanos')
const datase = require('../your/database/path')
const config = require('../your/configJson/path')
/**
* Application setup.
* @param {Object} api Express instance.
* @param {Object} options.config Application configs.
*/
module.exports = thanos((api, config) => {
// The database factory is only to illustration.
// The thanos package don't control your database instance.
const { repositories, storages } = database.factory(config.mongodb)
api.post('/', (storages) => {[
rescue(async (req, res) => {
//Do the magic!
res.status(201)
.json(data)
})
]})
api.get('/', (repositories) => {[
rescue(async (req, res) => {
//Do the magic!
res.status(200)
.json(data)
})
]})
api.delete('/:parameter', (storages) => {[
rescue(async (req, res) => {
await storages.someStorageInstance.delete(req.params.parameter)
res.status(204)
.end()
})
]})
})
it's only an example, please, read the 'GoodPratices' file to code it better.
Object Validation
When you receive a object at a route you may validate it before send to service layer, do it using the thanos validate function
.
At you middlwares route factory add a validate()
function that receive a 'ajv' object scheema validation that will validate your body scheema.
[...]
const { validate } = require('@shawee/thanos')
const factory = (service) => ([
/**
* Validating request payload
* ==========================
*/
validate({
type: 'object',
properties: {
data: {
type: 'object',
[...]
},
required: [ 'data', 'type' ]
}),
/**
* Request handler
* ===============
*/
rescue(async (req, res) => {
const provider = await service.create(req.body)
[...]
Validating a object
add a type: 'object'
propertie into { }
validate({
type: 'object',
properties: {
data: {
type: 'object',
[...]
}
}
})
Validating the object properties
Add a properties: {}
propertie into your object`
validate({
type: 'object',
properties: {
user: {
type: 'object',
properties:{
name: {
type: 'string'
}
}
},
isVerified: {
type: 'boolean'
}
}
})
Validate primitive properties
Add a type: 'String/Number/Boolean...'
property into your property subObject.
validate({
type: 'object',
properties: {
name: {
type: 'string',
[...]
},
verificatedUser: {
type: 'boolean',
[...]
},
age: {
type: 'number',
[...]
}
}
})
Validating the required properties
This validation only look to required properties, if you receive additional properties that doesn't in sheema validation, it will pass.
Inside the object and the subObjects, set a array property called required
with the required fields required: [ 'prop1', 'porp1' ]
.
That's in the same properties
property level.
validate({
type: 'object',
properties: {
porp1: {
[...]
},
pro2: {
[...]
},
pro3: {
[...]
}
},
required: [ 'porp1', 'pro3' ]
})
Validating property values
some properties only can have a specific value, so you can defing allpermited values using a unum type property:
Inside the object and the subObjects, set a array property called enum
and set yours permited values
validate({
type: 'object',
properties: {
porp1: {
type: 'string'
enum: [ 'value1', 'value2', 'value3']
},
pro3: {
[...]
}
},
required: [ 'porp1', 'pro3' ]
})
Complete example of a scheema validation
[...]
const { validate } = require('@shawee/thanos')
const factory = (service) => ([
/**
* Validating request payload
* ==========================
*/
validate({
type: 'object',
properties: {
company: {
type: 'object',
properties: {
name: {
type: 'object',
properties: {
fantasy: {
type: 'string'
},
corporative: {
type: 'string'
},
first: {
type: 'string'
},
last: {
type: 'string'
}
}
},
documents: {
type: 'object',
properties: {
cnpj: {
type: 'string'
},
cnae: {
type: 'string'
},
cnes: {
type: 'string'
},
cpf: {
type: 'string'
},
rg: {
type: 'string'
},
pis: {
type: 'string'
}
}
}
},
required: [ 'name', 'documents' ]
},
observation: {
type: 'string'
},
type: {
type: 'string',
enum: [ 'person', 'company' ]
}
},
required: [ 'data', 'type' ]
}),
/**
* Request handler
* ===============
*/
rescue(async (req, res) => {
const provider = await service.create(req.body)
[...]
More about thanos
Default Middlwares:
- 'morgan' Format:
:method :url :status :: :response-time ms
; - 'body-parser';
- 'helmet'
- Errors middlewares
- Errors render middlewares
Config
At factory method, we have a default configuration object that merge it the with your custom configuration object
[...]
const factory = (fn) => {
/**
* @function
* @param {Object} options Configurations object from config.js file.
* @param {String} environment Current environment name.
* @return {Object} Instance of express app.
*/
return (options, environment) => {
const config = merge({
name: env.get(['APP_NAME', 'npm_package_name'], 'app'),
version: env.get('GIT_RELEASE'),
morgan: {
format: `:method :url :status :: :response-time ms ${env.get('MORGAN_FORMAT')}`,
skip: (req, res) => environment !== 'development'
},
}, options)
[...]
You can create a custom config json and send it as parameter to factory function. That config file will be merged with default config..
[...]
/**
* Application setup.
* @param {Object} api Express instance.
* @param {Object} options.config Application configs.
*/
module.exports = thanos((api, config) => {
// The database factory is only to illustration.
// The thanos package don't control your database instance.
const { repositories, storages } = database.factory(config.mongodb)
[...]
Why Thanos name?
It's a reference to Thanos, he is a fictional character appearing in American comic books published by Marvel Comics. Created by writer/artist Jim Starlin, the character first appeared in The Invincible Iron Man #55 (cover dated February 1973).
The character appears in various Marvel Cinematic Universe films, portrayed by Damion Poitier in The Avengers (2012), and by Josh Brolin in Guardians of the Galaxy (2014), Avengers: Age of Ultron (2015), Avengers: Infinity War (2018), and the fourth Avengers film (2019) through voice and motion capture.
Coding style
Thanos package use Standard style guide, see more about at this 'link'
Up the server
After setup your index.js app file, let start the server into a other file called bin/www
, import the thanos's server object and call the start mathod sending a express instance and a config file(optinal).
const app = require('../your/index/app/path')
const config = require('../your/config/path')
const { server } = require('../../../packages/appify')
server.start(app, config)
Contributing
Please read CONTRIBUTING.md for details on our code of conduct, and the process for submitting pull requests to us.
Versioning
We use SemVer for versioning. For the versions available, see the tags on this repository.
Authors
- *Italo josé - Initial work - italojs
See also the list of contributors who participated in this project.
License
Don't have a license yet