MultiPaaS

Build on the generated API

MultiPaaS builds a GraphQL API from your model. This guide sets up your app's project to use it. Model your data first, with Model your data.

Set up the project

Run this in your app's own directory. APP_ID is the id that apps create printed. APP_TENANT_ID is the id that tenants create printed.

multipaas init --json --app APP_ID --tenant APP_TENANT_ID

To test in an environment other than the default, add --env ENV_ID, with an id from multipaas envs list --app APP_ID and an app-tenant of that environment. From CLI 1.2.0, init saves the environment of the app-tenant it pins in multipaas.json as environmentId, and your app's sign-in passes it as environment.

It writes multipaas.json, which pins your app to the newest API version. Commit multipaas.json. The JSON it prints holds the API's endpoints under endpoints. Put them in your app's config.

If the model is empty, the pin is empty too. Add your model first, then run multipaas pin.

Pull the schema

multipaas schema pull

It writes multipaas.graphql. Point your GraphQL codegen at that file.

Call the API

Send a POST to the GraphQL endpoint, endpoints.graphql from init, with the query and its variables as a JSON body and these headers:

A request without the version header gets HTTP 400. An unknown version gets 404. A list returns at most 100 items per page, so pageSize can be at most 100.

The access token comes from your end users signing in. See Add end-user sign-in.

A request over the account's API limit is refused with HTTP 429 and the code LIMIT_REACHED. Send no request to the API from any part of your app for the Retry-After seconds, or until extensions.resetsAt, and don't retry in a loop: the limit is the account's and a refused request still counts. Every app and MCP client on the account shares the limit, so they use it up during the pause too. See Limits.

Store files

An entity with a file field gets a request<Entity>FileUpload mutation. Its field input takes the file field's name. Storing a file takes three calls:

  1. Ask for an upload, giving the file's name, content type, size in bytes and SHA-256 as lowercase hex.
  2. PUT the bytes to the url it returns, with exactly its headers, within 15 minutes.
  3. Put the fileId it returned in the record's <field>FileId input when you create or update it.

Make the first and third calls as the same user, the one who asks for the upload. A token refreshed for that user works. The PUT sends only the headers it's given, never an access token.

This runs in the browser, with the signed-in user's token, for a Recipe entity with a photo file field. graphql is your function that POSTs the query and its variables to endpoints.graphql as JSON, with the three headers listed in Call the API, the access token included, and returns data, throwing unless the response is JSON with an object data and no errors:

async function uploadPhoto(recipeId: string, file: File): Promise<void> {
  const digest = await crypto.subtle.digest("SHA-256", await file.arrayBuffer());
  const sha256 = Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");
  const { requestRecipeFileUpload: upload } = await graphql(
    `
      mutation ($input: RequestRecipeFileUploadInput!) {
        requestRecipeFileUpload(input: $input) {
          fileId
          url
          headers {
            name
            value
          }
        }
      }
    `,
    {
      input: {
        field: "photo",
        filename: file.name,
        // A browser leaves the type empty for an extension it doesn't know.
        contentType: file.type || "application/octet-stream",
        sizeBytes: file.size,
        sha256,
      },
    },
  );
  const put = await fetch(upload.url, {
    method: "PUT",
    headers: Object.fromEntries(upload.headers.map((header) => [header.name, header.value])),
    body: file,
  });
  if (!put.ok) throw new Error(`Upload failed with HTTP ${put.status}`);
  await graphql(
    `
      mutation ($input: UpdateRecipeInput!) {
        updateRecipe(input: $input) {
          id
        }
      }
    `,
    {
      input: { id: recipeId, photoFileId: upload.fileId },
    },
  );
}

crypto.subtle exists only in a secure context, a page served over HTTPS or from localhost, so this example fails on a plain-HTTP address. file.arrayBuffer() holds the whole file in memory. Web Crypto has no incremental digest, so for a file too large for that, hash it in chunks with an incremental SHA-256 implementation.

On your server, the same three calls work with Node's fetch. Compute the hash with createHash("sha256") from node:crypto, and send the file's bytes as the body. Make the two API calls as one user: the end user, or your app identity for a background job.

Read the field to show the file. photo { filename url } returns a link that works for 15 minutes, so read it when you show the file. Files lists the limits and what each refusal means.

Once the account has used its monthly file download limit, the field comes back null with a LIMIT_REACHED error at its path, and the rest of the record still reads (Limits shows the error). The graphql function above throws on any error, so a page that should still show the record reads data and errors itself. Tell a refused file from an empty field by that error: show the file as unavailable until the error's resetsAt, and don't read the record again in a loop to get the link.

Update safely

When two requests can change the same record, pass the version you read as expectedVersion. version and expectedVersion need an API version made after they were added: pin one made since, because an older one doesn't have them. If your model has not changed since, make one with multipaas versions create, which needs CLI 1.10.0 or later. A stale version is refused with the code CONFLICT and writes nothing, so read again, work out the change again from what you read, and retry. If the re-read shows deletedAt set, the record was deleted; if it returns null, the caller can no longer read it. Either way, stop and report it, never recreate it or write the change somewhere else. An update of a record that was deleted, that the caller cannot read, or that the caller can read but may not change, is refused with NOT_FOUND: stop the same way. This protects a record only when every update to it passes expectedVersion: one update without it can overwrite a change it never saw. This keeps a daily limit in one counter record per day, such as one your app creates for each learner each day, as long as every request that adds to it checks the limit against the same read whose version it sends:

async function api(query, variables) {
  const response = await fetch(GRAPHQL_URL, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${accessToken}`,
      "X-MultiPaaS-App-Api-Version": API_VERSION,
    },
    body: JSON.stringify({ query, variables }),
  });
  return response.json();
}

async function useOne(counterId) {
  for (let attempt = 0; attempt < 5; attempt++) {
    const read = await api("query ($id: ID!) { counter(id: $id) { used version deletedAt } }", { id: counterId });
    if (read.errors || !read.data) throw new Error(read.errors?.[0]?.message ?? "unexpected response");
    const counter = read.data.counter;
    if (!counter || counter.deletedAt) throw new Error("the counter is gone");
    if (counter.used >= DAILY_LIMIT) return false;
    const write = await api("mutation ($input: UpdateCounterInput!) { updateCounter(input: $input) { used } }", {
      input: { id: counterId, expectedVersion: counter.version, used: counter.used + 1 },
    });
    if (write.data?.updateCounter) return true;
    const code = write.errors?.[0]?.extensions?.code;
    if (code !== "CONFLICT") throw new Error(write.errors?.[0]?.message ?? "unexpected response");
  }
  throw new Error("too many changes at once; try again later");
}

counter, used and UpdateCounterInput come from a Counter entity with a number field used. Use your own names from the schema.

The limit binds only callers who can't change the counter themselves. On a managed Counter entity, the default, a learner who created a counter manages it and can write any used. For a limit a learner must not get around, have your server create the counters and run useOne, signed in as an app identity, and use only counters it created itself, found by the id its create returned. Give learners' roles neither record.edit_all nor record.manage_all for counters, or for any entity above them: a role's permission on a parent entity also covers the entities that belong to it. Keep Counter managed, so no one gets a counter's access from its parent record.

Create test data

multipaas records create --entity ENTITY_ID --data '{"FIELD_ID": "value"}'

Key the data by field id, not field name. multipaas model show lists the ids. Then read the records back:

multipaas records list --entity ENTITY_ID

The records go to the test app-tenant in multipaas.json.

More