@crowdin/apps-storage
v0.31.0
Published
Transport-agnostic client for the Crowdin App Storage REST API: the data an installed Crowdin app keeps on the Crowdin side.
Readme
Crowdin Apps Storage
Transport-agnostic client for the Crowdin App Storage REST API (/api/v2/applications/{applicationIdentifier}/storage): the data an installed Crowdin app keeps on the Crowdin side. The key-value space (kv) is shared by all members of an app installation, with private per-user records under the reserved user:{id}: prefix, module-scoped records under the reserved module:{moduleKey}: prefix, and secret values encrypted at rest.
This package is the shared core of two SDK integrations - if you use either, you do not need it directly: @crowdin/serverless-apps-sdk/storage wires it to the Crowdin host bridge, and @crowdin/app-project-module exposes it as crowdinApp.crowdinStorage(crowdinId). Use this package directly only when you need a custom transport.
Installation
npm install @crowdin/apps-storageThe package has no runtime dependencies.
Usage
import { createStorage } from "@crowdin/apps-storage";
import type { StorageRequest, StorageResponse } from "@crowdin/apps-storage";
async function transport(request: StorageRequest): Promise<StorageResponse> {
const query = request.query ? `?${new URLSearchParams(request.query)}` : "";
const url = `https://api.crowdin.com/api/v2/applications/my-app/storage/${request.path}${query}`;
const res = await fetch(url, {
method: request.method,
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
},
body: request.body === undefined ? undefined : JSON.stringify(request.body),
});
const text = await res.text();
return {
status: res.status,
statusText: res.statusText,
body: text === "" ? undefined : JSON.parse(text),
};
}
const { kv } = createStorage({ transport, getUserId: () => "77" });
await kv.set("welcome-message", { text: "Hi!" });
const message = await kv.get<{ text: string }>("welcome-message");
await kv.user.set("gh-token", token, { secret: true });
const page = await kv.list({ prefix: "cfg_", limit: 100 });
const everything = await kv.withFetchAll().list();Semantics
setdefaults tokeyPolicy: "OVERRIDE": it POSTs first and on 409 falls back to a JSON Patchreplaceof/value(plus/ttlwhenttlwas passed - the stored TTL stays untouched otherwise).keyPolicy: "FAIL_IF_EXISTS"throwsKeyExistsErroron 409 instead. Clearing a TTL is not possible throughset; delete and re-create the key instead.secretapplies only when the key is created; overriding an existing key never changes its secret flag.getandgetWithMetadataresolveundefinedon 404;deleteis idempotent - deleting a missing key resolves.kv.user.*prefixes every key withuser:{id}:(the caller identity fromgetUserId) and strips that prefix from listed keys, so keys always read the way you wrote them.- A key under
module:{moduleKey}:scopes the record to that app module's surface: it exists only where the app runs as that module (the app's own token and the app's installer are not narrowed by module prefixes), listings skip the rest, and the API rejectssetunder a module key other than the current surface's (or an unknown one). Key positions are typed asKvKey, so editors suggest themodule:prefix; enumerate the app's module keys in the optional type parameter (createStorage<"main" | "reports">(...)) and they suggest the fullmodule:{moduleKey}:prefixes instead, while any other key stays accepted. listacceptsprefix,orderBy,limit, andoffset;orderBytakes the REST sort format (key,createdAt,updatedAt,expiresAt, each optionally followed bydesc, comma-separated - e.g."updatedAt desc,key"), and without it records come in a stable insertion order (oldest first) - a stable base order for offset paging.withFetchAll(maxAmount?)returns a copy of the scope whoselistwalks all pages sequentially (500 entries per request) up tomaxAmount; the caller'slimitandoffsetare ignored in that mode, theprefixandorderByare honored.
Errors
Non-2xx responses outside the special cases above reject with StorageApiError carrying status and the parsed Crowdin error payload. A status: 0 response (transport failure) is also a StorageApiError - it is never treated as a missing key or a conflict.
Transport contract
createStorage({ transport, getUserId }):
transport(request)receives{ method, path, query?, body? }wherepathis relative to the storage root -kv/recordsorkv/records/{urlencoded-key}. Prependapplications/{applicationIdentifier}/storage/and your API origin, serializequeryinto the URL, and resolve the raw HTTP response{ status, statusText?, body? }without throwing on non-2xx statuses.getUserId()returns the current user id forkv.user.*(a plain string or a promise of one). It is invoked lazily and awaited on every user-scoped operation and may throw when there is no authenticated user; when the option is omitted, anykv.user.*call rejects.
Limits
Enforced server-side: a key is 1..500 characters matching ^[a-zA-Z0-9:._-]+$, a value is up to 240 KiB of serialized JSON, a TTL is 60..31536000 seconds. A user:{id}: key prefix is reserved for the user with that id; a module:{moduleKey}: prefix is reserved for records scoped to that module; a key that starts with either reserved word but does not match the full prefix shape is rejected.
License
MIT
