Skip to main content

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 → Details
  • get(path, function) - Register GET route handlers → Details
  • put(path, function) - Register PUT route handlers → Details
  • patch(path, function) - Register PATCH route handlers → Details
  • delete(path, function) - Register DELETE route handlers → Details
  • all(path, function) - Register handlers for all HTTP methods → Details

Middleware & Authentication APIs

  • use(function) - Register global middleware → Details
  • auth(path, function) - Register authentication middleware → Details
  • static(options, function?) - Serve static files from source code → Details
  • storage(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 → Details
  • getOne(collection, query) - Get single document by ID/query → Details
  • findOne(collection, query) - Alias for getOne → Details
  • getMany(collection, query?, options?) - Get stream of documents → Details
  • find(collection, query?, options?) - Alias for getMany → Details
  • toArray(collection, query?, options?) - Get documents as array → Details
  • updateOne(collection, query, document, operators?, options?) - Update document (patch) → Details
  • updateMany(collection, query, document, operators?, options?) - Update multiple documents → Details
  • replaceOne(collection, query, document, options?) - Replace document completely → Details
  • replaceMany(collection, query, document, options?) - Replace multiple documents → Details
  • removeOne(collection, query) - Remove document → Details
  • removeMany(collection, query, options?) - Remove multiple documents → Details

Schema Management

  • setSchema(collection, schema) - Add JSON-Schema validation → Details
  • getSchema(collection) - Get collection schema → Details
  • removeSchema(collection) - Remove JSON-Schema validation → Details

Collection Management

  • createCollection(collection, options?) - Create new collection → Details
  • dropCollection(collection) - Delete collection → Details

Key-Value Store APIs

  • set(key, value, options?) - Set key-value pair with optional TTL → Details
  • get(key, options?) - Get value by key → Details
  • getAll(keyPattern, options?) - Get all key-value pairs matching pattern → Details
  • del(key, options?) - Delete key-value pair → Details
  • delAll(key, options?) - Delete all key-value pairs matching pattern → Details
  • incr(key, value, options?) - Increment numeric value → Details
  • decr(key, value, options?) - Decrement numeric value → Details

Queue & Background Processing APIs

  • queue(topic, function) - Register queue handlers → Details
  • worker(name, function) - Register worker functions → Details
  • enqueue(topic, document, options?) - Add job to queue → Details
  • enqueueFromQuery(collection, query, topic, options?) - Queue items from database query → Details

Job Scheduling APIs

  • job(cronExpression, function) - Register scheduled cron jobs → Details
  • schedule.runAt(when, data, worker) - Schedule one-time delayed job → Details
  • schedule.run(data, worker) - Execute worker immediately → Details

Workflow APIs

Workflow Management

  • createWorkflow(name, description, steps) - Create new workflow definition → Details
  • start(initialState) - Start new workflow instance → Details
  • updateState(instanceId, state, options?) - Update workflow state → Details
  • setState(instanceId, stateData) - Set complete workflow state → Details
  • continue(instanceId, reset?) - Continue paused workflow → Details
  • getWorkflowStatus(id) - Get workflow status → Details
  • getInstances(filter) - List workflow instances → Details
  • cancelWorkflow(id) - Cancel workflow instance → Details

Error Recovery & Monitoring

  • continueAllTimedOut() - Continue all timed out workflows → Details
  • findTimedOutSteps(filter?) - Find timed out workflow steps → Details

Event Management

  • on(event, listener) - Register event listener → Details
  • once(event, listener) - Register one-time event listener → Details
  • off(event, listener) - Remove event listener → Details
  • emit(event, data) - Emit custom event → Details

Configuration

  • configure(options) - Configure workflow settings → Details

File Management APIs

  • filestore.readFile(path) - Read file content as text → Details
  • filestore.readFileAsBuffer(path) - Read file content as buffer → Details
  • filestore.getReadStream(path) - Read file as binary stream → Details
  • filestore.saveFile(path, filestream) - Write binary stream to file → Details
  • filestore.deleteFile(path) - Delete file → Details
  • filestore.list(path) - List files in directory → Details

Real-time Communication APIs

  • realtime.createChannel(channel) - Create real-time channel → Details
  • realtime.publishEvent(channel, data, query?) - Publish event to channel → Details
  • realtime.createListener(channel, data) - Create listener for channel → Details
  • realtime.getListener(channel, listenerID) - Get specific listener → Details
  • realtime.getListeners(channel) - Get all listeners for channel → Details
  • realtime.removeListener(channel, listenerID) - Remove listener → Details

Template & Configuration APIs

  • set(key, val) - Set application configuration → Details
  • crudlify(schema?, options?) - Auto-generate CRUD REST API → Details

Application Lifecycle APIs

  • init(function?) - Initialize application and return manifest → Details
  • start(function?) - Alias for init() method → Details

Database REST API Endpoints

When using crudlify(), these endpoints are automatically created:

OperationMethodEndpointDescription
List allGET/:collectionGet all documents → Details
QueryGET/:collection?queryGet documents by query → Details
Get by IDGET/:collection/:idGet single document → Details
CreatePOST/:collectionCreate new document → Details
UpdatePATCH/:collection/:idUpdate document → Details
ReplacePUT/:collection/:idReplace document → Details
DeleteDELETE/:collection/:idDelete 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: