codehooks-js
Codehooks official helper library - provides Express.JS-like syntax for using codehooks.io (and more).
Read more in the docs: https://codehooks.io/docs/appeventapi.
Install
npm install codehooks-js -s
Usage
Example code for serverless backend API:
/*
* Express style Codehooks API
* Codehooks (c) example code.
*/
import {app, Datastore} from 'codehooks-js';
// global middleware
app.use((req, res, next) => {
console.log('Global hook middleware')
req.foo = 'bar'
next()
});
// middleware for routes
app.use('/hello', async (req, res, next) => {
console.log("Middleware for /hello route")
req.washere = true
next()
})
app.get('/hello', async (req, res) => {
console.log("GET")
const conn = await Datastore.open()
const doc = await conn.insertOne('greetings', {"message": "Hello World!", "when": new Date()})
res.json({...doc})
});
app.post('/hello', async (req, res) => {
const {body} = req
const conn = await Datastore.open()
// add POST data to worker queue
conn.enqueue('myQueueWorker', body)
res.status(201).json({"message": "thanks", "body": body})
})
app.job('*/30 * * * * *', async (data, job) => {
console.log("Tick")
// do some work each 30 second
job.end()
})
app.worker('myQueueWorker', async (data, job) => {
const {payload} = data.body
console.log("Message queue worker got item", payload)
// do some work with payload item from queue
job.end()
})
// return app to serverless runtime engine
export default app.init()
Tip: Check out the open source packages:
- https://www.npmjs.com/package/codehooks-crudlify - for automatic REST API generation
- https://www.npmjs.com/package/codehooks-mongodb - run apps locally or self hosting