WeWeb Backend Core
Core library for building and serving backend workflows in WeWeb applications.
This package provides the foundation for creating configurable, secure API
endpoints with flexible request handling and integration with external services.
Features
- API route handling and serving with Hono
- Dynamic workflow configuration and execution
- Security configuration with public/private access rules
- Advanced input validation and mapping
- Integration with external services via pluggable integrations
- Error handling and response formatting
- CORS support
- SSE streaming support
- Formula evaluation system
Installation
npm install @weweb/backend-core
pnpm add @weweb/backend-core
yarn add @weweb/backend-core
Basic Usage
import { serve } from '@weweb/backend-core';
const config = {
workflows: [
{
id: 'hello-workflow',
name: 'Hello API',
path: '/hello',
methods: ['GET'],
security: {
accessRule: 'public',
},
firstAction: 'hello_action',
actions: {
hello_action: {
id: 'hello_action',
type: 'action',
name: 'Say Hello',
actionId: 'example.say_hello',
inputMapping: {},
next: null,
},
},
},
],
integrations: [
{
slug: 'example',
_packageVersion: '1.0.0',
methods: {
say_hello: () => {
return { message: 'Hello from WeWeb Backend!' };
},
},
},
],
production: false,
};
serve(config);
console.log('Server running on http://localhost:8000');
Core Concepts
Backend Configuration
The backend configuration defines the structure for your backend server:
interface BackendConfig {
workflows: Workflow[]
integrations: Integration[]
production: boolean
rolesConfig?: RolesConfig
apiKey?: string
pathPrefix?: string
corsOptions?: CorsOptions
}
Workflows
Workflows define API endpoints with their HTTP methods, security settings, parameters validation, and actions:
interface Workflow {
id: string
name: string
metadata?: WorkflowMetadata
parameters?: Parameter[]
firstAction: string
firstErrorAction?: string | null
actions: Record<string, WorkflowAction>
}
interface WorkflowMetadata {
path?: string
method: HttpMethod
security?: SecurityConfig
}
interface Parameter {
type: 'string' | 'number' | 'boolean' | 'object' | 'array'
name: string
required?: boolean
}
interface SecurityConfig {
accessRule: 'public' | 'private'
accessRoles?: string[]
accessRolesCondition?: 'OR' | 'AND'
}
Integrations
Integrations allow external services to be accessed through defined methods:
interface Integration {
slug: string
_packageVersion: string
methods: {
[slug: string]: (...args: any[]) => MaybePromise<any>
}
}
Advanced Features
Input Validation
Define parameters for request validation:
const workflow = {
parameters: [
{
type: 'string',
name: 'name',
required: true
},
{
type: 'string',
name: 'email',
required: true
}
],
};
Security Rules
Configure endpoints with public or private access rules:
const workflow = {
metadata: {
security: {
accessRule: 'private',
accessRoles: ['admin', 'editor'],
accessRolesCondition: 'OR',
}
}
};
Multi-action Workflows
Chain multiple actions in a workflow and pass results between them:
const workflow = {
firstAction: 'get_data',
actions: {
get_data: {
id: 'get_data',
type: 'action',
name: 'Get Data',
actionId: 'example.getData',
inputMapping: {
id: '$query.id'
},
next: 'process_data',
},
process_data: {
id: 'process_data',
type: 'action',
name: 'Process Data',
actionId: 'example.processData',
inputMapping: {
data: '$results.get_data'
},
next: null,
},
},
};
SSE Streaming
Stream data to clients using Server-Sent Events by returning an AsyncIterator from your workflow:
const streamingAction = {
id: 'stream-data',
type: 'custom-js',
name: 'Stream Large Dataset',
inputs: {},
code: `
// Define an async generator function
async function* generateData() {
for (let i = 0; i < 100; i++) {
// Simulate processing time
await new Promise(resolve => setTimeout(resolve, 100));
yield { index: i, value: Math.random() * 100 };
}
}
// Return the async iterator directly
return generateData();
`,
next: null,
};
Custom CORS Configuration
Configure Cross-Origin Resource Sharing (CORS) options to control which domains can access your API:
const config = {
corsOptions: {
origin: ['https://app.example.com', 'https://admin.example.com'],
allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
allowHeaders: ['Content-Type', 'Authorization', 'X-Custom-Header'],
credentials: true,
maxAge: 3600,
exposeHeaders: ['Content-Length', 'X-Request-Id'],
}
};
If corsOptions
is not provided, a default permissive configuration is used:
origin: '*'
(allows requests from any domain)
- Standard HTTP methods
- Common headers like 'Content-Type' and 'Authorization'
Formula Evaluation
Use formulas to dynamically compute values from request data and previous action results:
const workflow = {
actions: {
some_action: {
inputMapping: {
computed: {
__wwtype: 'f',
code: 'context.http.query.id + context.http.body.data.value'
},
advancedComputed: {
__wwtype: 'js',
code: `
const id = parseInt(context.http.query.id);
const value = context.http.body.data.value;
return id + value;
`
}
}
}
}
};
Development
Testing
pnpm test
pnpm test --coverage
Code Quality
pnpm format
pnpm lint
pnpm typecheck
pnpm lint && pnpm typecheck
Related Packages
License
MIT