Skip to main content
Version: 0.4.2 (Previous)

📐 Schema

A schema forms the shape and provides validation for the data. Nodeblocks relies on JSON Schema Draft-07 which is both language-agnostic and tooling-friendly. To define schema we use withSchema primitive funciton.


1️⃣ Anatomy

src/schemas/review.ts
import { primitives } from '@nodeblocks/backend-sdk';

const { withSchema } = primitives;

const reviewIdPathParameter: primitives.OpenAPIParameter = {
in: 'path',
name: 'reviewId',
required: true,
schema: {
type: 'string',
},
};

export const reviewSchema: primitives.SchemaDefinition = {
$schema: 'http://json-schema.org/draft-07/schema#',
additionalProperties: false,
properties: {
productId: { type: 'string' },
rating: { type: 'number', minimum: 1, maximum: 5 },
comment: { type: 'string' },
},
type: 'object',
};

export const createReviewSchema = withSchema({
requestBody: {
content: {
'application/json': {
schema: { ...reviewSchema, required: ['productId', 'rating'] },
},
},
required: true,
},
});

export const updateReviewSchema = withSchema({
parameters: [{ ...reviewIdPathParameter }],
requestBody: {
content: {
'application/json': {
schema: {
additionalProperties: false,
properties: {
comment: { type: 'string' },
},
required: [],
type: 'object',
},
},
},
required: true,
},
});
  • withSchema(...) wraps the JSON definition and injects runtime validation.

2️⃣ Field Requirements

Required Fields

The required array in your schema determines which fields must be provided:

// This schema requires productId and rating
withSchema({
-- snap --
required: ['productId', 'rating'],
-- snap --
})

3️⃣ Additional Properties

It is possible to specify if the schema is allowed to accept additional (non-defined) properties by providing additionalProperties field with true value

{
-- snap --
additionalProperties: true, // allows additional properties
-- snap --
}

4️⃣ Validation Errors

When required fields are missing or invalid, the schema validation will throw errors before the request reaches your handlers:

// Missing required field
{
"error": {
"message": "Validation Error",
"data": [
"request body must have required property 'name'",
"request body must have required property 'status'"
]
}
}

➡️ Next

Learn about Validator » to see how to check data.