Raster

Client

createRasterClient, the functions for libraries, assets, uploads, variants, and search, and the image URL helpers and formatters.

createRasterClient creates a client for the Raster REST API. It runs in the browser and Node.js, and @raster-app/react re-exports it.

import {
  createRasterClient,
  listAssets,
  listLibraries,
  localStorageCredentialStore,
} from '@raster-app/sdk'

const raster = createRasterClient({
  host: { name: 'My App', openExternal: (url) => window.open(url, '_blank') },
  credentials: localStorageCredentialStore(),
})

const libraries = await listLibraries(raster, { organizationId: 'acme' })
const assets = await listAssets(raster, {
  organizationId: 'acme',
  libraryId: 'lib-1',
})

Create one client and reuse it. Each client keeps its own session.

Every function that calls Raster takes the client first. Your bundle keeps only the functions you import.

Configuration

OptionTypeDescription
hostRasterHostRequired. Your app's name and openExternal function. See The host.
credentialsCredentialStoreRequired. Where the credential is stored. See Where the credential is stored.

The host

host.name is your app's name on Raster's Connect page and in Profile settings → Connected apps.

host.openExternal(url) opens a URL in the user's browser: the sign-in page, and Open in Raster in RasterPicker. Its return value is ignored, so window.open and async functions both work.

Functions

FunctionResolves with
getMe(raster)The organizations and libraries the credential reaches.
listLibraries(raster, options)Every library in an organization.
listAssets(raster, options)One page of a library's assets.
getAsset(raster, options)One asset, with its variants.
uploadAsset(raster, options)The new asset, once Raster has the file.
waitUntilProcessed(raster, options)The processed asset, or null.
promoteVariant(raster, options)The ids the promote touches, once Raster accepts it.
waitUntilPromoted(raster, options)The asset once the promote lands, or null.
searchAssets(raster, options)One page of search results.
signInWithDevice(raster, options)The stored credentials. See Device sign-in.
connectApiKey(raster, { apiKey })The stored credentials. See API keys.
connectSharedApiKey(raster, { apiKey, organizationId })The credentials, in memory only. See Share an API key with every user.
checkApiKey(raster, { apiKey, organizationId })Nothing, once Raster accepts the key. See Check a key before saving it.
signOut(raster)Nothing. See Sign out.

Failed calls reject with a RasterApiError.

Cancelling a call

Library, asset, and search functions take an optional signal. Aborting it rejects the call with ABORTED; a signal from AbortSignal.timeout() rejects with TIMEOUT. isAbortError(error) tells a cancel from a failure:

import { isAbortError, searchAssets, toUserMessage } from '@raster-app/sdk'

const controller = new AbortController()

try {
  await searchAssets(raster, {
    organizationId: 'acme',
    query: 'sunset',
    signal: controller.signal,
  })
} catch (error) {
  if (!isAbortError(error)) alert(toUserMessage(error))
}

Sign-in takes a signal too.

What the credential reaches

getMe(raster) resolves with GET /me. To read it:

  • meOrganizationList(me): { id, name, libraryCount } per organization.
  • meOrganizations(me): { organizationId, organizationName, plan, libraries } per organization.
  • meLibraryAccess(me, organizationId, libraryId): 'read', 'write', or null.

Libraries

listLibraries(raster, { organizationId, organizationName?, signal? }) resolves with every Library in the organization, each with organizationId and organizationName (what you passed, or null).

Assets

listAssets(raster, { organizationId, libraryId, page?, pageSize?, signal? }) resolves with one page of assets. page starts at 1; pageSize defaults to 50. hasMorePages(pageLength, pageSize?) is true when a page came back full.

getAsset(raster, { organizationId, libraryId, assetId, signal? }) resolves with one asset and its variants.

Uploads

import { uploadAsset, waitUntilProcessed } from '@raster-app/sdk'

async function uploadFile(file: File) {
  const uploaded = await uploadAsset(raster, {
    organizationId: 'acme',
    libraryId: 'lib-1',
    source: file,
  })
  return waitUntilProcessed(raster, {
    organizationId: 'acme',
    libraryId: 'lib-1',
    assetId: uploaded.id,
    parentId: uploaded.parentId,
  })
}
OptionDescription
organizationId, libraryIdRequired. The target library.
sourceRequired. A Blob, a File, or { bytes, filename, contentType } with Uint8Array bytes.
filenameOverrides the source's name. An unnamed Blob is named upload.
parentIdUploads the file as a variant of this asset.
signalCancels the upload.

uploadAsset resolves once Raster has the file, with id, parentId, url, appUrl, and name. Raster then adds dimensions, sizes, and blurhash. waitUntilProcessed resolves with the processed Asset, or null if it's still processing when the wait ends. For a variant, it resolves with the parent. Limits and accepted files: POST …/assets.

Variants

import { promoteVariant, waitUntilPromoted } from '@raster-app/sdk'

const promotion = {
  organizationId: 'acme',
  libraryId: 'lib-1',
  assetId: 'abc123',
  variantId: 'var789',
}

await promoteVariant(raster, promotion)
const asset = await waitUntilPromoted(raster, promotion)

promoteVariant makes a variant the asset's default, served at the same URL. It resolves with assetId, promotedVariantId, and demotedVariantId (the new variant holding the previous default). waitUntilPromoted resolves with the asset once the promote lands, or null. Rules: POST …/promote.

import { searchAssets } from '@raster-app/sdk'

const { hits, found } = await searchAssets(raster, {
  organizationId: 'acme',
  query: 'sunset',
})

searchAssets resolves with one page of a SearchResult: assets whose name, description, or tags match, ranked by relevance.

OptionDescription
organizationIdRequired. The organization to search.
queryRequired. The search text.
libraryIdsLimits the search to these libraries. Defaults to every library the credential reaches.
pageThe page, starting at 1.
pageSizeHits per page. Defaults to 50.
signalCancels the search.

Blank queries and unreachable library ids: GET …/search/assets.

Session

Outside React, these functions read the credential in use. In React, use useSession().

import { isConfigured, loadSession, onSessionChange } from '@raster-app/sdk'

const credentials = await loadSession(raster)
console.log(isConfigured(credentials))

const unsubscribe = onSessionChange(raster, (next) => {
  console.log(isConfigured(next))
})
FunctionDescription
loadSession(raster)Reads the stored credential and resolves with it. Call it at startup, before the others.
getSession(raster)The stored credentials, or undefined until read.
onSessionChange(raster, listener)Calls listener with the credentials when they change. Returns an unsubscribe function.
isConfigured(credentials)true when there is a sign-in or an API key.
getCredentialIdentity(raster)An id for the credential in use, the same until the next sign-in. null when signed out.

Image helpers

Each helper takes an Asset, AssetVariant, or SearchHit.

HelperReturns
getThumbUrl(asset)A small URL for grids. undefined when there's none.
getPreviewUrl(asset)A large URL for previews. undefined when there's none.
getFullSizeUrl(asset)The full-size URL to hand your app on pick. null when there's none.
getBlurhashPlaceholder(asset)A blurred data: URL to show while loading. null without a blurhash or outside a browser.
isReady(asset)true once the asset is processed and has a full-size URL.

These URLs change when the asset's file is replaced, as by a promote.

To choose a size yourself:

  1. parseSizes(asset.sizes) returns an object from size to URL, or null.
  2. pickSizeUrl(sizes, targetEdge) returns the smallest size at least targetEdge pixels on its longest edge, or the largest one.
  3. versionedUrl(url, asset.contentVersion) makes the URL change when the file is replaced.

Formatters

Formatters match the Raster app: decimal units (1 MB is 1,000,000 bytes) and en-US dates.

FunctionReturns
formatBytes(bytes)512 B, 2 KB, 4.2 MB, 3.00 GB.
formatFileSize(bytes)formatBytes, or '' for null, undefined, negative, or non-finite.
formatDate(date)Jan 15, 2024.
formatDateLong(date)The date with weekday and time.
formatRelativeTime(date)just now, 5m ago, 3h ago, 2d ago, then formatDate from 7 days on.

Date formatters take a Date or Unix milliseconds (as in created and updated) and return '' for null.

Constants and types

ExportDescription
API_VERSIONThe Api-Version the client sends. See The Api-Version header.
ASSETS_PAGE_SIZE, SEARCH_PAGE_SIZEDefault pageSize for listAssets and searchAssets: 50.

Asset, AssetVariant, Library, Tag, Uploader, SearchHit, and SearchResult match the API's objects.

On this page