Skip to content

Entity Schema & Validation

Define entity schemas with validation rules in your tenant config. Validation runs both server-side and can be used client-side via the SDK.

Configuration

Add entities to your tenant config:

json
{
  "entities": {
    "definitions": {
      "User": {
        "name": "User",
        "description": "Application users",
        "tableName": "users",
        "fields": {
          "email": {
            "type": "text",
            "validation": { "required": true, "preset": "email" }
          },
          "name": {
            "type": "text",
            "validation": { "required": true, "min": 2, "max": 100 }
          },
          "age": {
            "type": "integer",
            "validation": { "min": 18, "max": 120 }
          },
          "status": {
            "type": "enum",
            "validation": { "enum": ["active", "inactive", "pending"] }
          }
        },
        "timestamps": true,
        "softDelete": true
      }
    },
    "validation": {
      "enabled": true,
      "strictMode": false,
      "sanitize": true
    }
  }
}

Field Types

TypeDescriptionExample
textVariable-length stringNames, descriptions
varcharFixed-length stringCodes, slugs
integerWhole numbersAge, count
bigintLarge integersIDs, timestamps
decimalFloating pointPrices, percentages
booleanTrue/falseFlags, toggles
timestampDate and timeCreated at
dateDate onlyBirth date
jsonJSON objectSettings, metadata
jsonbBinary JSONComplex data
arrayArray of valuesTags, categories
uuidUUID stringUnique identifiers
enumEnumerated valuesStatus, role

Validation Rules

Basic Rules

json
{
  "validation": {
    "required": true,
    "min": 3,
    "max": 100,
    "pattern": "^[a-z]+$",
    "message": "Custom error message"
  }
}
RuleTypeDescription
requiredbooleanField must have a value
minnumberMin length (strings) or value (numbers)
maxnumberMax length (strings) or value (numbers)
patternstringRegex pattern to match
presetstringUse a validation preset
enumstring[]Allowed values list
messagestringCustom error message

Validation Presets

Use presets for common validation patterns:

json
{
  "email": { "type": "text", "validation": { "preset": "email" } },
  "website": { "type": "text", "validation": { "preset": "url" } },
  "phone": { "type": "text", "validation": { "preset": "phone-us" } }
}
PresetDescriptionPattern
emailEmail addressuser@example.com
urlHTTP/HTTPS URLhttps://example.com
phone-usUS phone number(555) 123-4567
phone-intlInternational phone+1 555 123 4567
uuidUUID v1-5550e8400-e29b-41d4-a716-446655440000
slugURL slugmy-blog-post
usernameUsername (3-30 chars)john_doe123
passwordMin 8 characters********
namePerson nameJohn O'Brien
currencyCurrency amount123.45
percentage0-100 percentage85.5
dateISO date2024-01-15
datetimeISO datetime2024-01-15T10:30:00Z
timeTime14:30:00
ipIPv4 or IPv6192.168.1.1
ipv4IPv4 only192.168.1.1
ipv6IPv6 only2001:0db8::1
mac-addressMAC address00:1A:2B:3C:4D:5E
credit-cardCard number4111111111111111
postal-code-usUS ZIP code12345 or 12345-6789
ssnUS SSN format123-45-6789
hex-colorHex color#FF5733
jsonValid JSON string{"key": "value"}

Enum Validation

json
{
  "status": {
    "type": "enum",
    "validation": {
      "required": true,
      "enum": ["draft", "published", "archived"]
    }
  }
}

Entity Options

json
{
  "name": "Product",
  "tableName": "products",
  "description": "Product catalog",
  "timestamps": true,
  "softDelete": true,
  "generateRoutes": {
    "create": true,
    "read": true,
    "update": true,
    "delete": true,
    "list": true
  },
  "permissions": {
    "create": ["admin", "editor"],
    "read": ["admin", "editor", "viewer"],
    "update": ["admin", "editor"],
    "delete": ["admin"]
  }
}
OptionDefaultDescription
tableNamesnake_case of nameDatabase table/collection name
timestampstrueAdd created_at/updated_at
softDeletefalseAdd deleted/deleted_at fields
generateRoutesall trueAuto-generate CRUD routes
permissionsnoneRole-based access per operation

SDK Usage

Get Schema

typescript
const bf = await createBackflow({ clientKey: 'your-key' });

// Get all schemas
const schemas = await bf.entities.getSchema();

// Get schema for specific collection
const userSchema = await bf.entities.getCollectionSchema('users');

console.log(userSchema);
// {
//   collection: 'users',
//   fields: [
//     { name: 'id', source: 'builtin' },
//     { name: 'email', source: 'entity', type: 'text', required: true, preset: 'email' },
//     { name: 'age', source: 'entity', type: 'integer', min: 18, max: 120 }
//   ]
// }

Client-Side Validation

typescript
// Validate data before sending
const result = await bf.entities.validate('users', {
  email: 'invalid-email',
  age: 15
});

if (!result.valid) {
  console.log(result.errors);
  // [
  //   { field: 'email', message: 'email must be a valid email' },
  //   { field: 'age', message: 'age must be at least 18' }
  // ]
}

Create/Update with Validation

typescript
// Validates before sending to server
const { data, errors } = await bf.entities.createValidated('users', {
  email: 'user@example.com',
  name: 'John Doe',
  age: 25
});

if (errors) {
  // Handle validation errors
  console.error(errors);
} else {
  // Success
  console.log(data);
}

// Same for updates
const updateResult = await bf.entities.updateValidated('users', userId, {
  name: 'Jane Doe'
});

Admin UI

Use the Schema Builder in the admin dashboard to:

  1. Create/edit entities visually
  2. Add fields with type selection
  3. Configure validation rules via dropdowns
  4. Set presets without writing regex
  5. Preview and copy JSON config

Navigate to API & Data > Schema Builder in the admin panel.

API Response

The /admin/schema endpoint returns field validation info:

json
{
  "data": [
    {
      "collection": "users",
      "fields": [
        { "name": "id", "source": "builtin" },
        { "name": "created_at", "source": "builtin" },
        { "name": "email", "source": "entity", "type": "text", "required": true, "preset": "email" },
        { "name": "age", "source": "entity", "type": "integer", "min": 18, "max": 120 },
        { "name": "status", "source": "entity", "type": "enum", "enum": ["active", "inactive"] }
      ]
    }
  ]
}

Field sources:

  • builtin: System fields (id, created_at, updated_at, deleted, deleted_at)
  • route: Inferred from route definitions
  • entity: Defined in entity schema with validation

Examples

User Entity

json
{
  "User": {
    "name": "User",
    "fields": {
      "email": { "type": "text", "validation": { "required": true, "preset": "email" } },
      "password": { "type": "text", "validation": { "required": true, "preset": "password" } },
      "username": { "type": "text", "validation": { "required": true, "preset": "username" } },
      "role": { "type": "enum", "validation": { "enum": ["user", "admin", "moderator"] } },
      "profile": { "type": "jsonb" }
    },
    "timestamps": true
  }
}

Product Entity

json
{
  "Product": {
    "name": "Product",
    "tableName": "products",
    "fields": {
      "name": { "type": "text", "validation": { "required": true, "min": 3, "max": 200 } },
      "slug": { "type": "text", "validation": { "required": true, "preset": "slug" }, "unique": true },
      "price": { "type": "decimal", "validation": { "required": true, "min": 0 } },
      "status": { "type": "enum", "validation": { "enum": ["draft", "published", "archived"] } },
      "tags": { "type": "array" },
      "metadata": { "type": "jsonb" }
    },
    "timestamps": true,
    "softDelete": true
  }
}

Order Entity

json
{
  "Order": {
    "name": "Order",
    "fields": {
      "order_number": { "type": "text", "validation": { "required": true }, "unique": true },
      "customer_email": { "type": "text", "validation": { "required": true, "preset": "email" } },
      "total": { "type": "decimal", "validation": { "required": true, "min": 0 } },
      "status": { "type": "enum", "validation": { "required": true, "enum": ["pending", "paid", "shipped", "delivered", "cancelled"] } },
      "shipping_address": { "type": "jsonb", "validation": { "required": true } }
    },
    "timestamps": true,
    "softDelete": true,
    "permissions": {
      "create": ["admin", "system"],
      "read": ["admin", "user"],
      "update": ["admin"],
      "delete": ["admin"]
    }
  }
}

Released under the ISC License.