create a quick & tiny microservice api using zeit's micro
First, install Yeoman and generator-micro-api using npm (we assume you have pre-installed node.js).
npm install -g yo
npm install -g generator-micro-api
Then generate your new project:
yo micro-api
This just installs a bunch of useful API-related modules to throw together a microservice. The default template gives you a super-simple structure:
├── index.js
├── node_modules
├── package.json
└── yarn.lock
It makes a single-file microservice for you, defaulting to only accepting POST
requests, a compressed response, and simple readable errors to throw using micro-boom
.
Uses micro-post
by default, but has micro-get
for easily switching to a GET
service instead, and/or microrouter
for more complex stuff. Just import 'em and use 'em, they're installed already.
const { send, json } = require('micro')
const post = require('micro-post')
const compress = require('micro-compress')
const { handleErrors, createError } = require('micro-boom')
const cors = require('micro-cors')({
allowMethods: ['POST', 'OPTIONS'],
origin: '*'
})
let app = post(async(req, res) => {
const data = await json(req)
return data
})
app = handleErrors(app)
app = compress(app)
app = cors(app)
module.exports = app
GPL-3.0 © micah rich