@mutantlove/blocks v3.7.4
blocks
request|>think hard|>response.NodeJS API framework. Another one.
Features
Validate input
Pass request data (headers, body, query parameters, URL parameters) through custom JSON Schemas defined for each route. Make sure no unwanted data gets in, de-clutter the route logic and make the API behave more consistent.
If validation fails, an automatic409 Conflictresponse will be sent.
See ajv and JSON Schema docs for more on data validation.
Permissions
Simple function outside of main route logic.
If it returns false, an automatic403 Forbiddenresponse will be sent.
Promises
async/awaitin Plugins and Routes
Other
- File upload and form parsing for
multipart/form-data-busboy - Middleware support of existing package -
connect - JSON Web Token -
jsonwebtoken - Query string parsing -
qs - Route param parsing -
path-to-regexp - Cross-origin resource sharing -
cors - Secure your API with various HTTP headers -
helmet
Install
npm install @mutantlove/blocksExample
src/index.js
import http from "http"
import glob from "glob"
import { block } from "@mutantlove/blocks"
// initialize routes and plugins
const app = block({
// always scan relative to current folder
plugins: glob.sync("./plugins/*.js", { cwd: __dirname, absolute: true }),
routes: glob.sync("./**/*.route.js", { cwd: __dirname, absolute: true }),
})
// start node server using blocks middleware
app.then(([middleware, plugins]) => {
const server = http.createServer(middleware)
server.listen({
port: process.env.PORT,
})
server.on("error", error => {
console.log("Server error", error)
})
server.on("listening", () => {
console.log(`Server started on port ${process.env.PORT}`)
})
})
.catch(error => {
console.log("Application could not initialize", error)
})Configuration
blocks uses a set of process.env variables for configuration. See _env file for all available options and defaults.
We recommend using dotenv for easy local development and CI deployments.
Routes
Default "/ping" route
GET: /ping
{
"name": "foo",
"ping": "pong",
"aliveFor": {
"days": 2, "hours": 1, "minutes": 47, "seconds": 46
}
}Custom route
src/something.route.js
module.exports = {
method: "GET",
path: "/something/:id",
/**
* If req data is valid
* -> continue to permissionn check
* -> otherwise return 409
*/
schema: require("./something.schema"),
/**
* Permission checking, if allowed:
* -> continue to action
* -> otherwise return 403
*
* @param {Object} plugins Plugins
* @param {Object} req Node request
*
* @return {boolean}
*/
isAllowed: (/* pluginsObj */) => ({ method, ctx }) => {
console.log(`${method}:${ctx.pathname} - isAllowed`)
return true
},
/**
* After schema validation and permission checking, do route logic
*
* @param {Object} plugins Plugins
* @param {Object} req Node request
*
* @return {mixed}
*/
action: (/* pluginsObj */) => req => {
return {
message: "This ${req.ctx.params.id} is something else!"
}
},
}Custom JSON schema
A schema can contain only 4 (optional) keys:
headersvalidatesreq.headersparamsvalidatesreq.ctx.paramsparsed from URL withpath-to-regexpquery: validatesreq.ctx.queryparsed from URL withqsbodyvalidatesreq.ctx.bodyparsed fromreqwithJSON.parse
See src/plugins/route-default.schema.js for default values.
Each key needs to be a ajv compatible schema object.
src/something.schema.js
module.exports = {
headers: {
type: "object",
required: ["authorization"],
properties: {
authorization: {
type: "string",
},
},
},
params: {
type: "object",
additionalProperties: false,
required: ["id"],
properties: {
id: {
type: "string",
pattern: "^[a-z0-9-]+$",
maxLength: 25,
minLength: 25,
}
}
},
query: {
type: "object",
additionalProperties: false,
properties: {
offset: {
type: "integer",
minimum: 0,
default: 0,
},
limit: {
type: "integer",
minimum: 1,
maximum: 100,
default: 20,
},
},
},
}Plugins
Separate code interfacing with 3rd party libraries or services. pluginus dependency injection library is used.
Plugins are accesible in other plugins, middleware and routes.
Custom plugin
A plugin consists of a constructor function and a list of other plugins that is dependent on.
Whatever the create function returns will be considered as the plugin's content and is what will be exposed to the routes, middleware and other plugins.
src/plugins/database.js
const Sequelize = require("sequelize")
module.exports = {
/**
* Array of plugins to wait for before running `create`.
* Name is constructed from the filename by removing the extension and
* turning it into CammelCase.
*
* Ex. "test__name--BEM.plugin.js" => "TestNameBemPlugin"
*/
depend: ["Lorem"],
/**
* Constructor, return value will be considered the plugin's content exposed
* to routes, middleware and other plugins.
*
* @returns {Promise<any>} Plugin content
*/
create: => Lorem => {
console.log("Checking DB connection")
// Database connection, model loading etc
...
return {
Todos: ...,
Comments: ...,
}
}
}Develop
git clone git@github.com:mutantlove/blocks.git && \
cd blocks && \
npm run setupRun all *.test.js in tests folder
npm testWatch src and tests folders and re-run tests
npm run tddCommit messages
Using Angular's conventions.
<type>(<scope>): <subject>
<BLANK LINE>
<body>
<BLANK LINE>
<footer>
BREAKING CHANGE: Half of features not working anymore- feat: A new feature
- fix: A bug fix
- docs: Documentation only changes
- style: Changes that do not affect the meaning of the code (white-space, formatting, missing semi-colons, etc)
- refactor: A code change that neither fixes a bug nor adds a feature
- perf: A code change that improves performance
- test: Adding missing or correcting existing tests
- chore: Changes to the build process or auxiliary tools and libraries such as documentation generation
Changelog
See the releases section for details.