Codehooks.io API Cheat Sheet
Everything you need to build a serverless backend in one place. This cheat sheet contains all essential APIs for creating complete serverless applications with Codehooks.io. Quick reference for routing, authentication, NoSQL databases, workflows, queues, key-value stores, and real-time features. Each API includes direct links to detailed documentation with examples and usage patterns.
HTTP Routing APIs
post(path, function)
- Register POST route handlers → Detailsget(path, function)
- Register GET route handlers → Detailsput(path, function)
- Register PUT route handlers → Detailspatch(path, function)
- Register PATCH route handlers → Detailsdelete(path, function)
- Register DELETE route handlers → Detailsall(path, function)
- Register handlers for all HTTP methods → Details
Middleware & Authentication APIs
use(function)
- Register global middleware → Detailsauth(path, function)
- Register authentication middleware → Detailsstatic(options, function?)
- Serve static files from source code → Detailsstorage(options, function?)
- Serve files from blob storage → Details
Database/NoSQL APIs
Connection & Setup
Datastore.open()
- Connect to datastore and return API interface → Details
Document Operations
insertOne(collection, document)
- Insert new document → DetailsgetOne(collection, query)
- Get single document by ID/query → DetailsfindOne(collection, query)
- Alias for getOne → DetailsgetMany(collection, query?, options?)
- Get stream of documents → Detailsfind(collection, query?, options?)
- Alias for getMany → DetailstoArray(collection, query?, options?)
- Get documents as array → DetailsupdateOne(collection, query, document, operators?, options?)
- Update document (patch) → DetailsupdateMany(collection, query, document, operators?, options?)
- Update multiple documents → DetailsreplaceOne(collection, query, document, options?)
- Replace document completely → DetailsreplaceMany(collection, query, document, options?)
- Replace multiple documents → DetailsremoveOne(collection, query)
- Remove document → DetailsremoveMany(collection, query, options?)
- Remove multiple documents → Details
Schema Management
setSchema(collection, schema)
- Add JSON-Schema validation → DetailsgetSchema(collection)
- Get collection schema → DetailsremoveSchema(collection)
- Remove JSON-Schema validation → Details
Collection Management
createCollection(collection, options?)
- Create new collection → DetailsdropCollection(collection)
- Delete collection → Details
Key-Value Store APIs
set(key, value, options?)
- Set key-value pair with optional TTL → Detailsget(key, options?)
- Get value by key → DetailsgetAll(keyPattern, options?)
- Get all key-value pairs matching pattern → Detailsdel(key, options?)
- Delete key-value pair → DetailsdelAll(key, options?)
- Delete all key-value pairs matching pattern → Detailsincr(key, value, options?)
- Increment numeric value → Detailsdecr(key, value, options?)
- Decrement numeric value → Details
Queue & Background Processing APIs
queue(topic, function)
- Register queue handlers → Detailsworker(name, function)
- Register worker functions → Detailsenqueue(topic, document, options?)
- Add job to queue → DetailsenqueueFromQuery(collection, query, topic, options?)
- Queue items from database query → Details
Job Scheduling APIs
job(cronExpression, function)
- Register scheduled cron jobs → Detailsschedule.runAt(when, data, worker)
- Schedule one-time delayed job → Detailsschedule.run(data, worker)
- Execute worker immediately → Details
Workflow APIs
Workflow Management
createWorkflow(name, description, steps)
- Create new workflow definition → Detailsstart(initialState)
- Start new workflow instance → DetailsupdateState(instanceId, state, options?)
- Update workflow state → DetailssetState(instanceId, stateData)
- Set complete workflow state → Detailscontinue(instanceId, reset?)
- Continue paused workflow → DetailsgetWorkflowStatus(id)
- Get workflow status → DetailsgetInstances(filter)
- List workflow instances → DetailscancelWorkflow(id)
- Cancel workflow instance → Details
Error Recovery & Monitoring
continueAllTimedOut()
- Continue all timed out workflows → DetailsfindTimedOutSteps(filter?)
- Find timed out workflow steps → Details
Event Management
on(event, listener)
- Register event listener → Detailsonce(event, listener)
- Register one-time event listener → Detailsoff(event, listener)
- Remove event listener → Detailsemit(event, data)
- Emit custom event → Details
Configuration
configure(options)
- Configure workflow settings → Details
File Management APIs
filestore.readFile(path)
- Read file content as text → Detailsfilestore.readFileAsBuffer(path)
- Read file content as buffer → Detailsfilestore.getReadStream(path)
- Read file as binary stream → Detailsfilestore.saveFile(path, filestream)
- Write binary stream to file → Detailsfilestore.deleteFile(path)
- Delete file → Detailsfilestore.list(path)
- List files in directory → Details
Real-time Communication APIs
realtime.createChannel(channel)
- Create real-time channel → Detailsrealtime.publishEvent(channel, data, query?)
- Publish event to channel → Detailsrealtime.createListener(channel, data)
- Create listener for channel → Detailsrealtime.getListener(channel, listenerID)
- Get specific listener → Detailsrealtime.getListeners(channel)
- Get all listeners for channel → Detailsrealtime.removeListener(channel, listenerID)
- Remove listener → Details
Template & Configuration APIs
set(key, val)
- Set application configuration → Detailscrudlify(schema?, options?)
- Auto-generate CRUD REST API → Details
Application Lifecycle APIs
init(function?)
- Initialize application and return manifest → Detailsstart(function?)
- Alias for init() method → Details
Database REST API Endpoints
When using crudlify()
, these endpoints are automatically created:
Operation | Method | Endpoint | Description |
---|---|---|---|
List all | GET | /:collection | Get all documents → Details |
Query | GET | /:collection?query | Get documents by query → Details |
Get by ID | GET | /:collection/:id | Get single document → Details |
Create | POST | /:collection | Create new document → Details |
Update | PATCH | /:collection/:id | Update document → Details |
Replace | PUT | /:collection/:id | Replace document → Details |
Delete | DELETE | /:collection/:id | Delete document → Details |
Authentication Methods
- API Tokens - Use
x-apikey
header for app-to-app authentication → Details - JWT/JWKS - Configure JWT authentication via Auth0, Clerk, etc → Details
- Custom Auth - Use
codehooks-auth
package for complete control → Details
Query Syntax Examples
NoSQL Queries
// Simple equality
{
status: 'active';
}
// Comparison operators
{
age: {
$gt: 18;
}
}
{
price: {
$lte: 100;
}
}
// Logical operators
{
$and: [{ status: 'active' }, { age: { $gte: 18 } }];
}
// Array operations
{
tags: {
$in: ['javascript', 'nodejs'];
}
}
// Regular expressions
{
name: {
$regex: /john/i;
}
}
URL Query Parameters
# Simple query
?status=active&limit=10
# Advanced query
?q={"age":{"$gt":18}}&sort=name&fields=name,email
Common Usage Patterns
Basic API Setup
import { app } from 'codehooks-js';
// Auto-generate CRUD API
app.crudlify();
// Custom routes
app.get('/hello', (req, res) => {
res.json({ message: 'Hello World' });
});
export default app.init();
Database Operations
import { Datastore } from 'codehooks-js';
async function myFunc() {
const conn = await Datastore.open();
// Insert document
const doc = await conn.insertOne('users', { name: 'John' });
// Query documents
const users = await conn.getMany('users', { active: true }).toArray();
// Key-value operations
await conn.set('session:123', { userId: 'abc' }, { ttl: 3600000 });
}
...
Background Processing
// Register worker
app.worker('emailWorker', async (req, res) => {
console.log('Processing email:', req.body.payload);
res.end();
});
// Queue job
async function myFunc() {
const conn = await Datastore.open();
await conn.enqueue('emailWorker', { email: '[email protected]' });
}
...
Workflow Processing
// Create a workflow with persistent state
const workflow = app.createWorkflow(
'orderProcessing',
'Process customer orders',
{
start: async (state, goto) => {
state.orderId = state.orderId || generateOrderId();
goto('validatePayment', state);
},
validatePayment: async (state, goto) => {
// Validate payment logic here
if (state.paymentValid) {
goto('fulfillOrder', state);
} else {
goto('handlePaymentError', state);
}
},
fulfillOrder: async (state, goto) => {
state.status = 'fulfilled';
goto(null, state); // Complete workflow
},
}
);
// Start workflow instance
const orderWorkflow = await workflow.start({
customerId: '123',
amount: 99.99,
});
Links: