1.9.0 • Published 3 years ago

@owessels/backend-api v1.9.0

Weekly downloads
-
License
ISC
Repository
github
Last release
3 years ago

Backend API

Getting started

  1. Install this package npm install @owessels/backend-api.
  2. Create an index.ts file and create your backend definition using builder functions provided by this package e.g:
import {
    BackendDefinition,
    createDataTypeBuilder,
    createSchemaBuilder,
    createValidationsBuilder,
} from '@owessels/backend-api';

const dataType = createDataTypeBuilder();
// Define your entity types and how they link to each other.
const schema = createSchemaBuilder()
    .addEntityType('task', {
        name: 'Task',
        buildFields: builder =>
            builder
                .addSimpleField('name', dataType.string())
                .addSimpleField('completed', dataType.boolean())
                .build(),
    })
    .build();
// Define permissions for viewing entities and validations 
const validations = createValidationsBuilder(schema)
    .add('task', {
        validateUpdate: async () => ({ valid: true }),
        // Allow any logged in user to view a 'task'
        readPermissions: {
            anonymous: predicate => predicate.constant(false),
            user: predicate => predicate.constant(true),
        },
    })
    .build();

type Schema = typeof schema;

// Export your backend definition. Note, this export MUST be named 
// 'backendDefinition' and have the correct type.
// Do not include anything else in this file.
export const backendDefinition: BackendDefinition<Schema, {}> = {
    schema,
    validations,
    functions: {},
};

Creating a local client

You can develop your app using the in-memory backend client.

  1. Create a backend client using initInMemoryBackend, e.g.
import { initInMemoryBackend } from '@owessels/backend-api';
// Import your backendDefinition from the file where you created it above.
import { backendDefinition } from '<path-to-your-backend-definition>';

const backendClient = initInMemoryBackend({ backendDefinition });
  1. Skip ahead to creating your first entity to see how to create data.

Deploying your backend

  1. Create an instance using the backend UI, copy your instance ID.
  2. Execute the provided backend binary to deploy your backend, passing in your instance ID and path to main file containing your backendDefinition e.g. yarn backend deploy --instance abc-123 --main ./src/backend/index.ts

Creating a production client

  1. Deploy your backend using the steps in deploying your backend.
  2. Create a backend client using initBackend, e.g.
import { initBackend } from '@owessels/backend-api';
// Import your backendDefinition from the file where you created it above.
import { backendDefinition } from '<path-to-your-backend-definition>';

const backendClient = initBackend({
    // Paste your instance ID here.
    instanceId: '<your-instance-id>',
    backendDefinition,
});

Creating your first entity

await backendClient.database.createSourceEntity('task', {
    fieldValues: {
        name: 'My first task!',
        completed: false,
    },
});

Querying entities

// Fetch all tasks
const subscription = backendClient.database.createSourceQuerySubscription(
    {
        sourceEntityTypeKey: 'task',
        // Provide type-safe filtering and ordering of entities
        filters: {},
        orderBy: [],
    },
    update => {
        // Called whenever the query changes.
        console.log(update.entities);
    },
);

// Make sure to call subscription.unsubscribe() when you no longer need it. 
// E.g. if you are using React, when the component unmounts.