@weweb/backend-core
TypeScript icon, indicating that this package has built-in type declarations

0.2.48 • Public • Published

WeWeb Backend Core

npm version

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
npm install @weweb/backend-core

# pnpm
pnpm add @weweb/backend-core

# yarn
yarn add @weweb/backend-core

Basic Usage

import { serve } from '@weweb/backend-core';

// Define your backend configuration
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,
};

// Start the server
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 {
  /** Unique identifier for this workflow */
  id: string

  /** Name of the workflow */
  name: string

  /** Metadata for the workflow including path, method and security */
  metadata?: WorkflowMetadata

  /** Parameters for request inputs validation */
  parameters?: Parameter[]

  /** ID of the first action to execute in the workflow */
  firstAction: string

  /** ID of the first action to execute in the error path, or null if not handled */
  firstErrorAction?: string | null

  /** Map of actions keyed by their ID */
  actions: Record<string, WorkflowAction>
}

interface WorkflowMetadata {
  /** URL path for this endpoint (e.g., "/users" or "/products/:id") */
  path?: string

  /** HTTP method this endpoint supports (GET, POST, etc.) */
  method: HttpMethod

  /** Security configuration for this endpoint */
  security?: SecurityConfig
}

interface Parameter {
  /** Type of the parameter */
  type: 'string' | 'number' | 'boolean' | 'object' | 'array'

  /** Name of the parameter */
  name: string

  /** Whether this parameter is required */
  required?: boolean
}

interface SecurityConfig {
  /** Whether the endpoint is public or private */
  accessRule: 'public' | 'private'

  /** List of roles that have access when accessRule is "private" */
  accessRoles?: string[]

  /** How to combine multiple roles: "OR" (any role grants access) or "AND" (all roles required) */
  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', // User needs to be either admin OR editor
    }
  }
  // ...
};

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:

// Example of a workflow action that returns an AsyncIterator
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 = {
  // ...other config properties
  corsOptions: {
    // Allow requests only from specific origins
    origin: ['https://app.example.com', 'https://admin.example.com'],

    // Specify allowed HTTP methods
    allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],

    // Allow specific headers
    allowHeaders: ['Content-Type', 'Authorization', 'X-Custom-Header'],

    // Enable credentials (cookies, auth headers)
    credentials: true,

    // Cache preflight requests for 1 hour (in seconds)
    maxAge: 3600,

    // Expose these headers to the browser
    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

# Run all tests
pnpm test

# Run tests with coverage
pnpm test --coverage

Code Quality

# Format code
pnpm format

# Run linter
pnpm lint

# Check types
pnpm typecheck

# Combined code quality check
pnpm lint && pnpm typecheck

Related Packages

License

MIT

Readme

Keywords

none

Package Sidebar

Install

npm i @weweb/backend-core

Weekly Downloads

145

Version

0.2.48

License

none

Unpacked Size

108 kB

Total Files

5

Last publish

Collaborators

  • kram
  • aureliev
  • leo.coletta