The official JavaScript/TypeScript library for Codehooks.io - a serverless backend platform that provides everything you need to build and deploy backend applications.
Codehooks.io is a complete serverless backend platform that combines:
- Database - NoSQL document storage with MongoDB-like queries
- API Server - Express.js-style routing and middleware
- Background Jobs - Queues, workers, and scheduled tasks
- Real-time - Server-sent events for live updates
- File Storage - Static file serving and blob storage
- Workflows - Step-based application logic
All in one platform with zero infrastructure management.
Install the Codehooks CLI:
$ npm install -g codehooks
Install the codehooks-js library in your project:
npm install codehooks-js
Example code for a serverless backend API and NoSQL database:
/*
* REST API with NoSQL database storage.
* Codehooks (c) example code.
*/
import {app, datastore} from 'codehooks-js';
// Example GET route and a NoSQL database insert operation
app.get('/myroute', 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})
});
// Serve web content from the uploaded directory /static
app.static({directory: "/static"})
// CRUD REST API for any collection
app.crudlify({}, {prefix: "/"})
// return app to serverless runtime engine
export default app.init()
Rename the index.js to index.ts or create a new index.ts file. Start developing using TypeScript and strong types shown in the example code below.
/*
* REST API with NoSQL database storage.
* Codehooks (c) example code in TypeScript.
*/
import {app, datastore, httpResponse, httpRequest} from 'codehooks-js';
// Example GET route and a NoSQL database insert operation
app.get('/myroute', async (req: httpRequest, res: httpResponse) => {
console.log("GET")
const conn = await datastore.open()
const doc = await conn.insertOne('greetings', {"message": "Hello World!", "when": new Date()})
res.json({...doc})
});
// Serve web content from the uploaded directory /static
app.static({directory: "/static"})
// CRUD REST API for any collection
app.crudlify({}, {prefix: "/"})
// return app to serverless runtime engine
export default app.init()
When running the coho compile
command, it will automatically create a tsconfig.json
file in the project directory. The tsconfig file can be further adapted to your needs, the initial configuration is shown in the example below:
{
"files": [
"./index.ts"
],
"compilerOptions": {
"allowJs": true,
"lib": [
"ES6",
"dom"
]
}
}
Any syntax or type error will be displayed accordingly from the compile command, for example:
$ coho compile
🤔 [tsl] ERROR in /Users/jane/projects/tsdemo/index.ts(9,9)
TS2345: Argument of type '(req: httpRequest, res: httpResponse) => void' is not assignable to parameter of type 'string'.
Correcting the errors should ultimately show a successfull compile output, ready for deployment of your backend app.
$ coho compile
OK 🙌
Your backend application is now available at your project's endpoint URL. For example:
https://myproject-ff00.codehooks.io/dev/*
From the project directory run:
$ codehooks deploy
For complete documentation, visit https://codehooks.io/docs.
The Codehooks class provides a comprehensive backend application framework with the following APIs:
-
post(path, ...hook)
- Register POST route handlers -
get(path, ...hook)
- Register GET route handlers -
put(path, ...hook)
- Register PUT route handlers -
patch(path, ...hook)
- Register PATCH route handlers -
delete(path, ...hook)
- Register DELETE route handlers -
all(path, ...hook)
- Register handlers for all HTTP methods
-
use(...hook)
- Register global middleware (supports string paths, RegExp, or function) -
useRoute(route, ...hook)
- Register route-specific middleware -
auth(path, ...hook)
- Register authentication middleware for specific paths
-
queue(topic, ...hook)
- Register queue handlers for background processing -
worker(name, ...hook)
- Register worker functions (also adds to queues for legacy support) -
job(cronExpression, ...hook)
- Register scheduled cron jobs
-
static(options, hook)
- Serve static files from source code directory -
storage(options, hook)
- Serve files from blob storage directory
-
set(key, val)
- Set application configuration settings -
render(view, data, cb)
- Render templates with data -
crudlify(schema, options)
- Auto-generate CRUD REST API endpoints
-
realtime(path, ...hook)
- Set up server-sent events (SSE) channels for real-time communication
-
createWorkflow(name, description, steps, options)
- Create and register a new workflow instance
-
init(hook)
- Initialize the application and return manifest -
start(hook)
- Alias forinit()
method
The Codehooks class serves as a comprehensive backend application framework that combines HTTP routing, background processing, real-time communication, and workflow management capabilities in a single, cohesive API.
The Datastore provides a unified interface for both NoSQL document storage and Key-Value operations. It supports MongoDB-like query syntax and provides streaming capabilities for large datasets.
-
open()
- Connect to the Datastore and return the API interface -
collection(name)
- Get a NoSQL collection by name for document operations
-
getOne(collection, query)
- Get a single document by ID or query -
findOne(collection, query)
- Alias for getOne -
getMany(collection, query?, options?)
- Get a stream of documents matching query -
find(collection, query?, options?)
- Alias for getMany
-
insertOne(collection, document)
- Insert a new document into a collection -
updateOne(collection, query, document, updateOperators?, options?)
- Update one document (patches existing data) -
updateMany(collection, query, document, updateOperators?)
- Update multiple documents -
replaceOne(collection, query, document, options?)
- Replace one document completely -
replaceMany(collection, query, document, options?)
- Replace multiple documents
-
removeOne(collection, query)
- Remove one document by ID or query -
removeMany(collection, query)
- Remove multiple documents matching query
-
createSchema(collection, schema)
- Validate collection data against JSON-Schema -
setSchema(collection, schema)
- Alias for createSchema -
removeSchema(collection)
- Remove JSON-schema validation for collection -
getSchema(collection)
- Get JSON-schema for collection
-
count(collection)
- Count documents in a collection
-
set(key, value, options?)
- Set a key-value pair -
get(key, options?)
- Get a value by key -
getAll(keyPattern, options?)
- Get all key-value pairs matching pattern -
del(key, value)
- Delete a key-value pair -
delAll(keyPattern, options?)
- Delete all key-value pairs matching pattern
-
incr(key, value, options?)
- Increment a numeric value -
decr(key, value, options?)
- Decrement a numeric value
-
enqueue(topic, document, options?)
- Add a job to a queue for background processing -
enqueueFromQuery(collection, query, topic, options?)
- Queue each item from a database query
When using getMany()
or find()
, you get a DataStream object with these methods:
-
on(event, callback)
- Listen for data events (e.g.,'data'
,'end'
) -
json(response)
- Pipe data directly to HTTP response as JSON -
toArray()
- Convert stream to array of objects -
forEach(callback)
- Iterate over each object in the stream
import { datastore } from 'codehooks-js';
// Connect to datastore
const conn = await datastore.open();
// NoSQL operations
const doc = await conn.insertOne('users', { name: 'John', email: 'john@example.com' });
const user = await conn.getOne('users', { _id: doc._id });
const users = await conn.getMany('users', { active: true }).toArray();
await conn.updateOne('users', { _id: doc._id }, { lastLogin: new Date() });
// Key-Value operations
await conn.set('user:123:session', { token: 'abc123', expires: new Date() });
const session = await conn.get('user:123:session');
await conn.incr('visits', 1);
// Queue operations
await conn.enqueue('emailWorker', { to: 'user@example.com', template: 'welcome' });
The Datastore supports MongoDB-like query syntax:
// Simple equality
{ status: 'active' }
// Comparison operators
{ age: { $gt: 18 } }
{ price: { $lte: 100 } }
// Logical operators
{ $and: [{ status: 'active' }, { age: { $gte: 18 } }] }
{ $or: [{ category: 'A' }, { category: 'B' }] }
// Array operations
{ tags: { $in: ['javascript', 'nodejs'] } }
{ tags: { $all: ['javascript', 'nodejs'] } }
// Regular expressions
{ name: { $regex: /john/i } }
Many operations accept an options object for additional configuration:
// Upsert option for updates
await conn.updateOne('users', { email: 'john@example.com' },
{ lastLogin: new Date() }, {}, { upsert: true });
// Key-Value options
await conn.set('key', 'value', { ttl: 3600000 }); // 1 hour TTL
- Express-style routing with support for all HTTP methods
- Middleware system with global and route-specific middleware
- Background processing with queues, workers, and scheduled jobs
- Static file serving from both source and blob storage
- Real-time communication via Server-Sent Events
- Workflow engine for complex step-based applications
- Auto-generated CRUD APIs with schema validation
- Template rendering system
- Singleton pattern for global application state
- Datastore with MongoDB-like query syntax, key-value operations, and queue management