JS20

Documentation

JS20 - Documentation

Helper schemas

Schemas are just objects, so you can join them together like this:

const sCar: Car = {
    registrationNumber: sString().type(),
};

const sOwner: Owner = {
    name: sString().type(),
    age: sNumber().min(0).type(),
};

const combined: Car & Owner = {
    ...sCar,
    ...sOwner,
};

/*
Combined becomes:
{
    registrationNumber: sString().type(),
    name: sString().type(),
    age: sNumber().min(0).type(),
}
*/

Instance schemas

Often you want to return a database instance from your endpoint, which contains the fields id, createdAt, updatedAt and ownerId as well as your custom properties. You can do it by using the helper function Schema.withInstance(), which appends these fields to your existing schema:

app.addEndpoint({
    path: '/cars',
    method: 'POST',
    inputSchema: sCar,
    outputSchema: Schema.withInstance(sCar),
    isLoggedIn: true,
    run: async (system, input) => {
        return system.models.car.create(input);
    }
});

These two are the same:

const sCarWithInstance = Schema.withInstance(sCar);

And this:

const sCarWithInstance = {
    ...sCar,
    id: sString().type(),
    createdAt: sDate().type(),
    updatedAt: sDate().type(),
    ownerId: sString().type(),
};

Id schemas

Schema.withId() adds an ID property to your schema.

const sCarWithId = Schema.withId(sCar);

Which is the same as:

const sCarWithId = {
    ...sCar,
    id: sString().type(),
};
JS20