Generate a typed client
Every site defines its own templates: a page template with its own fields, a store with its own product templates, a catalog with its own parts. Code that reads such a site cannot be typed from a fixed package — the shapes live in that site's content database.
@snolla/content-schema-gen reads the templates of one site and writes two files for the front
end that reads it.
| File | What is inside |
|---|---|
types.ts |
One interface per template, the shapes of the site's entities, and a constant object with the template identifiers |
client.ts |
SiteContentClient — typed methods over @snolla/content-api-client: one family per page set, store, blog and catalog on this site. Tables and feeds are not generated; they are read through the transport client's own modules |
Both are derived data. Do not edit them by hand. Keep the output directory out of version control —
add it to .gitignore — unless you deliberately commit the models; either way, the generator owns
the content of those files.
What the generator needs
The tool reads templates straight from the site's database, not through the content API. Two
things must be in the config the process runs with, read with node-config
from the project's config/ directory (config/default.json for a single site):
| Setting | Meaning |
|---|---|
siteId |
The site whose templates are read. --site overrides it |
data.provider |
Connection to that site's database: dialect and dsn |
{
"siteId": "<your-site-id>",
"data": {
"provider": {
"dialect": "postgres",
"dsn": "<database-dsn>"
}
}
}
Install and run
npm install --save-dev @snolla/content-schema-gen
npm install @snolla/content-api-client
npx content-schema-gen --site <siteId> --output ./src/generated
@snolla/content-api-client is a runtime dependency, not a development one: the generated client
imports it. Wiring the generator into prepare regenerates the models on every install:
{
"scripts": {
"prepare": "content-schema-gen --output ./src/generated"
}
}
| Option | Meaning |
|---|---|
--site <id> |
Site to generate for (default: siteId from the config) |
--output <dir> |
Where the files are written (default: ./generated) |
--watch |
Regenerate whenever the templates change |
--interval <ms> |
Polling period of --watch (default: 30000) |
--serve |
Run as a small HTTP service instead |
--port <n> |
Port of --serve (default: 3334) |
The run is the same in all three modes: read the templates, write types.ts and client.ts,
overwriting the previous output. They land in <output> — except in server mode, which writes them
under <output>/<siteId>.
Watch mode polls the templates every --interval milliseconds, compares them with the previous
poll and regenerates only when their content changed, so a running front end picks the new shapes
up without a manual step.
Server mode generates on request and writes into a per-site subdirectory, <output>/<siteId> —
one output root can serve several sites:
curl -X POST 'http://localhost:3334/regenerate?site=<siteId>'
A request that is not POST /regenerate answers 404; a request without ?site= answers 400
with Missing ?site=<siteId>; a successful run answers 200 OK.
Use the generated client
SiteContentClient extends the transport client, so it takes the same two constructor arguments:
the base URL of the content API, and an optional API key sent as a bearer token.
import config from 'config';
import { SiteContentClient } from './generated/client.js';
import { PAGE_TEMPLATE_IDS } from './generated/types.js';
const client = new SiteContentClient(config.get('contentApi.baseUrl'));
// A site that needs a key: new SiteContentClient(baseUrl, process.env.CONTENT_API_KEY)
const page = await client.getPageViewModel('/');
if (page.template.id === PAGE_TEMPLATE_IDS.MAIN_PAGE) {
console.log(page.headline); // the fields of this template — autocompleted
console.log(page.meta_description);
}
PageViewModel is a union of the site's page templates, discriminated by template.id, so the
narrowed branch carries exactly the fields that template declares. The constant object
PAGE_TEMPLATE_IDS maps a template alias — uppercased, dashes and spaces turned into underscores —
to its identifier; compare identifiers, never aliases.
Store products, blog posts and catalog products follow the same rule, with their own unions and
their own constant objects (MAIN_STORE_PRODUCT_TEMPLATE_IDS, NEWS_BLOG_POST_TEMPLATE_IDS,
PARTS_CATALOG_PRODUCT_TEMPLATE_IDS). A store product carries a variants[] typed per variant
template.
Each entity — store, blog, catalog — gets one interface with no union at all: its fields come from
its own definition, not from a template. A site with two blogs and two catalogs gets four: one per
entity, named by its alias. Methods are named
get<Entity><Parent><Resource>, where <Entity> is the entity alias in Pascal case (or the first
eight characters of its identifier, dashes removed, when no alias is set). For a store with alias
main, a blog news and a catalog parts:
const store = await client.getMainStoreViewModel();
const categories = await client.getMainStoreCategories();
const category = await client.getMainStoreCategoryViewModel('shoes');
const inCategory = await client.getMainStoreCategoryProducts(category.id, 20, 0);
const tags = await client.getMainStoreTags();
const vendors = await client.getMainStoreVendors();
const products = await client.getMainStoreProducts(20, 0);
const product = await client.getMainStoreProductViewModel('my-slug');
const blog = await client.getNewsBlogViewModel();
const blogCategory = await client.getNewsBlogCategoryViewModel('release-notes');
const posts = await client.getNewsBlogCategoryPosts(blogCategory.id, 20, 0);
const catalog = await client.getPartsCatalogViewModel();
const part = await client.getPartsCatalogProductViewModel('rotor-12');
Product and post list wrappers exist only when the parent has at least one product or post
template. Vendors exist on stores only. Two site-wide reads are always generated:
getStaticPage(path) for raw static pages and getRobotsTxt().
These entity list methods take a window as (limit, offset), both optional, in that order —
getMainStoreProducts(20, 0) is the first twenty products. For page-based paging, filters and
facets, use the page listing below.
List pages with the selection language
The template-typed reads above are lookups. Everything that selects — filters, sorting, paging
through a large listing, facet counts — goes through the page listing, which the same client
reaches as client.pages.queryPages:
const result = await client.pages.queryPages({
template: 'catalog-product',
path: '/parts',
filter: { price: '1000..5000', 'spec.material': 'steel' },
sort: 'price:asc',
page: 2,
hitsPerPage: 24,
facets: ['spec.material'],
});
// result: { pages, limit, offset, total, facets? }
The answer reports the window it used as limit and offset, whatever spelling the request
arrived with; Selecting content covers the window and the refusals.
| Key | Meaning |
|---|---|
template |
Template alias the listing is narrowed by |
path |
Children of this path — one level, not the whole subtree |
filter |
One entry per declared field path: value |
sort |
<field-path> or <field-path>:asc / <field-path>:desc; a bare word is a named order — relevance, newest |
page |
One-based page number (default 1) |
hitsPerPage |
Page size, 1…200 (default 24) |
facets |
Declared filterable field paths whose value counts come back in result.facets |
Each filter entry is sent as its own query parameter, filter[<field-path>]=<value>, which is
why the object is keyed by field path rather than by a flat name. A facet never narrows itself: the
counts for a value list ignore the filter on that same path.
client.pages.queryPagesBody sends the same request as a JSON body to POST /pages/query — the
same validator, one meaning. client.pages.getPageFilters returns the filter panel: declared
filterable paths with their values and counts.
Field names that are not identifiers
A field name in the admin is data: 3dview, 9axis, street view are legal, and real templates
use them. The rule is the TypeScript one: a key that is a valid identifier is written bare,
anything else is written quoted —
export interface PartsCatalogProductViewModel {
headline: string;
'3dview': string;
}
— so 3dview is reachable as item['3dview'], never as item.3dview. Names that are
identifiers, including non-Latin ones, stay bare: item.headline, item.поле.
Regenerate when templates change
Templates change in the admin, so the models must follow. Run the generator again — through
npm run prepare, through --watch, or through the server-mode request above — and commit the
result if you keep the output in the repository.
An edit that removes a template drops it from the generated union and from the constant object, and code that still compares against it stops compiling — which is the point of generating from the site rather than hand-writing its models.
When it stops
| Message | Cause and fix |
|---|---|
siteId not found: pass --site <siteId> or set siteId in config |
Neither the flag nor siteId in the config — set one |
the config names no data.provider |
No database connection in the config — add data.provider.dialect and data.provider.dsn |
types.ts no longer parses |
Output written by a version whose quoting rule was narrower than this one — regenerate |
Related
- CLI reference — scaffolding a site, running it locally, moving content.
- Admin API reference — templates and fields are created and edited through the admin API.