Code generation

Generate a typed client for your buckets and typed callers for your HTTP functions from a live instance.

The CLI reads the buckets and functions of the current context and generates TypeScript you can use in apps and functions.

Bucket ORM

Terminal
spica bucket orm --path ./src/spica
Text
✔ Succesfully completed! File url is /home/me/app/src/spica/bucket.ts

bucket.ts contains an interface per bucket and a typed cursor per bucket, built on @spica-devkit/bucket:

Generated (excerpt)
export interface Posts<Relations extends string[] = [], Localize extends boolean = true> {
  _id?: string;
  title: Localize extends true ? string : {"tr_TR": "string", "en_US": "string"};
  slug: string;
  status?: ("draft" | "published");
  tags?: string[];
  author?: Find<Relations, "author">[] extends never[] ? string : (Authors<FindRest<Relations, "author">[]> & id);
  views?: number;
  published_at?: Date | string;
}

export const posts = new PostsCursor("6b0b1968a5611972c29c25f7", Bucket.data, PostsRelationFields);

Use it with chained query options:

TypeScript
import {initialize, posts} from "./spica/bucket";

initialize({apikey: process.env.SPICA_API_KEY});

const latest = await posts
  .filter('document.status == "published"')
  .sort({published_at: -1})
  .limit(10)
  .resolveRelations(["author"])
  .getAll();

latest[0].author.name; // typed, because the author relation was resolved

await posts.insert({title: {en_US: "Typed!"}, slug: "typed"});
Cursor methodEffect
filter(expression), sort(object), limit(n), skip(n)Query options.
paginate()Return {meta, data}.
translate(language)Request a language.
nonLocalize()Return every language.
resolveRelations(paths)Resolve relations, with typed results.
get(id), getAll()Read.
insert(doc), update(doc), patch(doc), remove(id)Write.

initialize is pre-configured with the context's URL. Install @spica-devkit/bucket in the project that uses the file, and regenerate it whenever schemas change.

Function ORM

Terminal
spica function orm --path ./src/functions --trigger-types http

For every function with an HTTP trigger, the CLI writes <function>/index.js and index.d.ts with a caller per handler, using axios:

Generated hello/index.js (excerpt)
import axios from "axios";
export default function (config) {
  config = {...config, method: "get", url: "http://localhost:4500/api/fn-execute/hello"};
  return axios.request(config).then(r => r.data);
}
TypeScript
import hello from "./src/functions/hello";

const result = await hello({params: {name: "Ada"}});
OptionDefaultDescription
--pathCurrent directoryOutput folder.
--trigger-typeshttpTrigger types to generate callers for.
--http-serviceaxiosHTTP library used by the generated code.