Skip to content
LogoLogo

How to store data for an installation

This guide shows you how to keep data for one installation of your app in Picked. Each installation owns a set of labels. Your server keeps settings, IDs and credentials there, and needs no database of its own.

You need an app with a server that uses @picked/app-kit, and the private key of the app. Build and install your first app makes these.

1. Make an installation client

Each label operation goes through an installation client. Make the client from the request that your server answers:

RequestClient
A lifecycle event, an app event or a tool callinstallationClientFor(event, { privateKey })
A request from a page of the appinstallationClientFor(session, { privateKey, sessionToken: sessionTokenOf(request) })
Work outside a request, with offlineAccesscreateInstallationClient({ apiUrl, installationId, privateKey })

A request from Picked contains a token for the installation. The client uses that token. For a page request, the client gets a token with the session token of the person. For more about tokens, refer to How to read project data from an app.

The installation token reads and writes the labels of its own installation. It needs no scope for this. The scopes of the manifest do not change it.

src/server.ts
import {
  createAppHandler,
  installationClientFor,
  json,
  readAppEnvironment,
  readSession,
  sessionTokenOf,
} from '@picked/app-kit/server'
import { serve } from '@picked/app-kit/node'
 
const port = process.env.APP_PORT ?? '4103'
const { privateKey, pickedKeys } = readAppEnvironment(process.env, port)
 
const handler = createAppHandler({
  pickedKeys,
  async onInstall(event) {
    const client = installationClientFor(event, { privateKey })
    await client.labels.set([
      { namespace: 'settings', key: 'installed_at', type: 'text', value: new Date().toISOString() },
    ])
  },
  async fallback(request) {
    const { pathname } = new URL(request.url)
    if (pathname === '/api/settings') {
      const session = await readSession(request, pickedKeys)
      if (session === null) return json({ error: 'unauthenticated' }, 401)
      const client = installationClientFor(session, {
        privateKey,
        sessionToken: sessionTokenOf(request),
      })
      return json({ labels: await client.labels.list() })
    }
    return json({ error: 'not_found' }, 404)
  },
})
 
serve(handler, Number(port))

2. Set labels

Call client.labels.set with a list of labels. Each label has a namespace, a key, a type and a value. A namespace and a key each have 1 to 64 characters: lowercase letters, digits, _ or -. The value is a string that you write as the type.

await client.labels.set([
  { namespace: 'crm', key: 'account_id', type: 'text', value: 'acct_4821' },
  { namespace: 'crm', key: 'sync_enabled', type: 'boolean', value: 'true' },
  { namespace: 'crm', key: 'batch_size', type: 'number', value: '50' },
  {
    namespace: 'crm',
    key: 'field_map',
    type: 'json',
    value: JSON.stringify({ email: 'Email', company: 'Company' }),
  },
])

set makes each label, or replaces the label with the same namespace and key. Labels that the call does not name do not change. set returns labels, the labels that it set, and skipped.

Use these options when you need them:

  • A credential. Set secret: true. Picked keeps the value in its secret store. Only a text or json label can be secret.
  • A value for a limited time. Set expiresIn to a number of seconds, from 1 to 31536000. After that time, list and get do not return the label.
  • A counter. Give increment in place of value on a number label.
  • A value that only one writer can set. Set onlyIfAbsent: true. Picked writes the label only when no label with that namespace and key exists. An expired label counts as absent.
  • All the labels or none. Give { atomic: true } as the second argument. If one onlyIfAbsent label cannot be written, set writes no label.
await client.labels.set([
  { namespace: 'crm', key: 'refresh_token', type: 'text', value: refreshToken, secret: true },
  { namespace: 'crm', key: 'synced_count', type: 'number', increment: 1 },
])

A secret label cannot have increment or onlyIfAbsent. Labels tells how expiry, increments and conditional writes work.

3. Let one process do a task at a time

To let only one process do a task at a time, set a label with onlyIfAbsent and expiresIn. If a different process holds the label, set returns it in skipped:

const lockId = crypto.randomUUID()
const { skipped } = await client.labels.set([
  {
    namespace: 'sync',
    key: 'lock',
    type: 'text',
    value: lockId,
    onlyIfAbsent: true,
    expiresIn: 300,
  },
])
if (skipped.length > 0) return
 
try {
  await syncContacts()
} finally {
  await client.labels.delete([{ namespace: 'sync', key: 'lock', ifValue: lockId }])
}

With ifValue, delete removes the label only when it holds that value. If the label expires and a different process sets it, delete keeps that label.

4. Read labels

Call client.labels.list() for all the labels of the installation. Call client.labels.get(namespace, key) for one label. get returns undefined when the label does not exist or is expired.

const accountId = (await client.labels.get('crm', 'account_id'))?.value
const fieldMap = await client.labels.get('crm', 'field_map')
const map: unknown = fieldMap === undefined ? {} : JSON.parse(fieldMap.value)

Each value is a string. Parse it as its type. A token of the installation reads the value of a secret label. Each label also has secret, expiresAt and updatedAt.

5. Remove labels

Call client.labels.delete with the namespace and key of each label. It returns the IDs of the labels that it removed.

await client.labels.delete([
  { namespace: 'crm', key: 'refresh_token' },
  { namespace: 'crm', key: 'account_id' },
])

6. Handle a refused write

When Picked refuses a label, set and delete throw LabelWriteError. Its userErrors tell which label and why:

import { LabelWriteError } from '@picked/app-kit/server'
 
try {
  await client.labels.set(labels)
} catch (error) {
  if (!(error instanceof LabelWriteError)) throw error
  for (const { field, message, code } of error.userErrors) {
    console.warn(`${field.join('.')}: ${message} (${code})`)
  }
}

An installation has these limits:

LimitMessage
100 labelsAn app installation holds at most 100 labels.
65,536 bytes for each valueAn app installation label holds at most 65536 bytes.

Both errors have the code LABEL_WRITE_INVALID. When Picked refuses one label of a call, it writes no label of that call.

7. Know who can see the labels

The labels belong to the installation, with the owner type APP_INSTALLATION:

  • A person with organization_apps/read on the project can read the labels. The value of a secret label is empty for a person.
  • A person with organization_apps/update on the project can set and remove them.
  • The installation reads and writes them with its own tokens, without a scope.

When a person removes the app from a project, Picked first sends installation.deleted to your server. The labels are still there, so your server can read a credential and revoke it at the other service. Then Picked deletes the labels and the installation. Picked deletes them also when your server does not answer or answers with an error. Refer to How to connect an external service with OAuth.