We've just released the open source package codehooks-mongodb on NPM. It's an implementation of a codehooks.io backend using Node.js Express and MongoDB. It is entirely compatible with codehooks.io, so you get an easy way to develop APIs with built-in access to a document database, a key value store, Worker Queues and CRON jobs.
Codehooks simplifies API backend development by combining serverless JavaScript functions and fast database persistence with a coherent and well documented API. Apps are instantly deployable and scaleable to the cloud.
One of the great things about the codehooks-mongodb package is that it provides flexibility in terms of deployment options. With this package, you can develop and run a serverless node.js app locally, and you can deploy it to your favorite cloud infrastructure or self-host it.
Additionally, if you prefer a more hands-off approach, you can deploy your app to the codehooks.io SaaS service, which also supports this package. Do check out the codehooks.io docs or the features page for more detailed examples and information.
To use codehooks-mongodb, we start with creating a standard serverless codehooks.io backend app with the necessary routes and event handlers.
Check out the full source code for the example app developed in this blog post at Github.
Installingโ
Create a new folder "myapp" to develop the app source code. Then install all the necessary dependencies from npm. Please note that Codehooks uses JavaScript ES6. Tip: use npm init es6
command to initialize our package.json
correctly.
mkdir myapp
cd myapp
npm init es6 -y
npm install codehooks-mongodb codehooks-js codehooks-crudlify express body-parser mongodb debug yup --save
npm install codehooks -g
If you don't have a MongoDB instance already, you you can start a local MongoDB as a docker container.
docker run -d -p 27017:27017 --name mongodb mongo:latest
Now that we have all dependencies installed we can start creating a new backend app.
A practical code exampleโ
Lets start by creating a simple CRUD backend for user
data. To kick-start the development we're using the open source package Crudlify.
๐ฅ Crudlify automagically creates a complete REST API and database persistence for any data schema provided. Define your data schema with Yup or JSON-schema and Crudlify will take care of the rest.
In this app we've created a simple Yup data schema for users
.
The minimal version of the backend app is shown in the example below.
import app from 'codehooks-js'
import crudlify from 'codehooks-crudlify'
import {user} from './schema.js'; // Yup data schema definition
// Add CRUD routes for a user schema - collection
crudlify(app, {user})
export default app.init() // export app scope to serverless runtime
For better readability and separation of logic the Yup data schema is defined in a separate JavaScript file schema.js
.
import * as yup from 'yup'
// Schema for users
export const user = yup.object().shape({
name: yup.string().required(),
email: yup.string().email().required(),
active: yup.boolean().default(true)
})
As a complete Codehooks app this can now be initialized and deployed with the codehooks CLI command coho init
and coho deploy
.
Additionally, as this blog post shows, you can develop and run the same app locally using the open source package codehooks-mongodb. This brings great flexibility and freedom in terms of how and where to deploy backend apps.
Run the app as a local Express serverโ
A standard codehooks app is executed by the cloudbased serverless runtime engine - codehooks.io.
To run the same app locally we can provide an alternative runtime engine. This is exactly what the codehooks-js
and codehooks-mongodb
packages are solving by using Express and mongoDB.
The code example in app.js
below shows how to implement a Node.js Express server as a runtime engine for the Codehooks app in index.js
.
/*
* app.js
* Example express app for running codehooks.io standalone using mongoDB
*/
import express from 'express';
import bodyParser from 'body-parser';
import mongoStore from 'codehooks-mongodb';
import codehooks from './index.js';
const app = express();
app.use(bodyParser.json({ limit: '1mb' }));
const options = {
"datastore": new mongoStore('mongodb://localhost:27017')
}
// important, make codehooks use express and mongoDB
codehooks.useExpress(app, options);
const server = app.listen(8080, () => {
console.log('Listening on port:', server.address().port);
});
In the startup file, use body-parser
middleware to parse incoming request bodies, and create an instance of codehooks-mongodb
with the mongoDB connection string. Finally, use the useExpress()
method of the codehooks app instance to mount it on the express.js app instance.
Start the local serverโ
Start the server with the standard node
command, note that we're starting app.js
and not index.js
.
node app.js
If everything goes well, the following output should show in the console.
Listening on port: 8080
Once the app is started, it can run locally on any machine, on a preferred cloud server, or on the codehooks.io SaaS platform, giving you the flexibility to choose how and where to deploy your app.
Lets test some Crudlify magicโ
Insert a new user
to the databaseโ
POST a new user using curl.
curl -X POST \
'http://localhost:8080/dev/user' \
--header 'Content-Type: application/json' \
--data-raw '{
"name": "Ally",
"email": "[email protected]"
}'
Validate data with Yupโ
Check that the data schema validates correctly by sending an invalid email address.
curl -X POST \
'http://localhost:8080/dev/user' \
--header 'Content-Type: application/json' \
--data-raw '{
"name": "Sally",
"email": "sally.example.com"
}'
Validation error shows that Yup works.
400 Bad Request
{
"value": {
"active": true,
"email": "sally.example.com",
"name": "Sally"
},
"path": "email",
"type": "email",
"errors": [
"email must be a valid email"
],
... # chopped error message
}
Run a query against the databaseโ
curl -X GET \
'http://localhost:8080/dev/user?name=Ally' \
--header 'Content-Type: application/json'
Example output.
[
{
"_id": "63fb97825f624f479034eb08",
"active": true,
"email": "[email protected]",
"name": "Ally"
}
]
Update a record in the databaseโ
curl -X PATCH \
'http://localhost:8080/dev/user/63fb97825f624f479034eb08' \
--header 'Content-Type: application/json' \
--data-raw '{
"name": "Ally Mc. Beal"
}'
Read more about how to query and update your database in the Crudlify package.
The codehooks-mongodb package is a great option for flexibility and to avoid service lock-in. Additionally, the codehooks.io documentation provides information on how to use the built-in database connection, the key-value store, queue workers, and CRON jobs to build more complex and scalable applications.