A platform for community discussion. Free, open, simple.
name: discourse-warpdrive-models description: Use when creating a new WarpDrive-backed frontend model, or when reading, using, or changing a model already converted to WarpDrive (anything under frontend/discourse/app/data or extending RestCompatModel/WarpRestModel)
WarpDrive models
service:warp-store (services/warp-store.js) is a second data store alongside the legacy service:store, built on @warp-drive/* in LegacyMode with a JSON:API cache. Migrated models live in frontend/discourse/app/data/:
schemas/— one resource schema per type, registered inschemas/index.jsnormalize.js+jsonapi-utils.js— Discourse REST payloads → JSON:API documentsbuilders/— request objects, one file per resourcehandlers/discourse-rest.js— the sole network handler; routes throughajax()warp-rest-model.js—WarpRestModelwrapper base, pluswarpStore(),requestMany/requestOne,defineFieldForwardersrest-compat.js—RestCompatModel, temporary legacyRestModelsurface (get/set/setProperties, drafts, legacy adapter save path)extra-attributes.js— retains payload keys no schema declares (migration safety net)
A model is converted if its class in app/models/ extends RestCompatModel (or WarpRestModel directly) and its schema is listed in schemas/index.js.
Note: Schemas must be complete
A record is a proxy over the cache; reading a field the schema doesn't declare throws in dev/test and returns undefined in production. Object.keys, for...in, and toJSON see only schema fields. Therefore:
- Declare more attributes than seems necessary — a field only one endpoint sends still needs a line.
- To find every field, read the Ruby serializers (
app/serializers/, including subclasses andadd_to_serializercalls) and the API JSON schemas (spec/requests/api/schemas/json/) — not just one sample payload. - Anything still arriving via
extra-attributes.jsis unfinished work, not a pattern to rely on.
Creating a new model
Schema —
data/schemas/<type>.js, usingwithDefaults+attrs/belongsTofromschemas/helpers.js. Annotate with/** @type {import("@warp-drive/core/types/schema/fields").LegacyResourceSchema} */(avoids a TS2883 d.ts issue). Register it inschemas/index.js.Normalizer — in
data/normalize.js(or a per-resource file), build{ data, included, meta }. UseresourceFrom(type, Schema, raw)for the resource object (it also feeds the extras registry; pass an explicitidfor sub-resources),indexIncluded+maybeRelatefor relationships —maybeRelatedrops pointers with no matchingincludedentry, on purpose. Absent payload →{ data: null }, never{ data: [] }for single-record ops (wrap with therecordOnlypattern).Builders —
data/builders/<resource>.jsusingreadMany/readOne/createOne/updateOne/deleteOnefrombuilders/helpers.js; they carry theopand thedata: { type, id }the cache needs. RPC-style endpoints (toggles, bulk ops) are plain inline{ url, method, options }objects with noop.Model class — in
app/models/, extendRestCompatModel(only extendWarpRestModeldirectly if no caller uses the legacy store/get/setAPI):export default class Badge extends RestCompatModel { static type = "badge"; static normalize = normalizeBadgesPayload; static builders = { list: findBadges, one: findBadge, save: saveBadge, delete: deleteBadge, }; // custom getters here take precedence over forwarders } defineFieldForwarders(Badge, BadgeSchema);Other subclass hooks:
- endpoints beyond plain CRUD — own statics over
requestMany/requestOne(seeUserBadge.findByUsername), not morebuilderskeys static munge(json)— massages JSON on legacy_hydrateprimaryKey—TagNotificationuses"name"__resourceoverride, for models with their own ingest path — call_applyExtraAttributes(id)after pushing, and read__ownResourcein anything the base constructor reaches, since subclass fields aren't initialized duringsuper()
- endpoints beyond plain CRUD — own statics over
Run the model's qunit tests plus acceptance tests for its screens.
Relations to unmigrated models (User, Topic, …) are not relationships: store the raw embedded object as a plain attribute (see bookmark.js user, or userBadgeResource inlining sideloads), optionally wrapping it in the legacy model class in a getter or create.
Working with a converted model
Reading and mutating:
- Fields are prototype forwarders to the cached record:
badge.namereads,badge.name = xwrites (LegacyMode records are mutable). Relationships are read-only through the wrapper. - Legacy
get("a.b")/set/setPropertiesstill work viaRestCompatModel. - Ids are strings in the cache; the
@idforwarder (schema.identity.name, usuallyid) coerces numeric ones back to numbers.peekRecordneedsString(id). - Wrap a nested cached resource in its own model class in a getter when callers need that class's getters (
get badge() { return new Badge(this.__resource.badge) }). - Probe field existence by reading (
record.foo !== undefined), never within— thehastrap on drafttrackedObjects is unreliable and can hang headless qunit. - List results are arrays with document
metaassigned onto them (result.grant_count).
Fetching and persisting:
Model.findAll(opts)/Model.findById(id)— viabuilders.list/one. Anything else:requestMany(this, someBuilder(...))/requestOne(...).Model.createFromJson(json)— synchronous ingest for preloaded/embedded payloads;record.updateFromJson(json)re-pushes and re-adopts.- Legacy
store.createRecord(type, attrs)still works: it produces a draft wrapper (__isLocalDraft, attrs in atrackedObject, undeclared keys readable). Aftersave()the wrapper adopts the cached record and strict schema reads apply. record.save(data)has two paths: withstatic builders.saveit goes through WarpDrive (store.request); without, it falls back to the legacy adapter pipeline. Both fireaddModelCallbackhooks and mergeaddModelSavePropertyextras.record.destroy()(builder path) vsrecord.destroyRecord()(legacy adapter path).- One-off actions:
warpStore().request(someBuilder(...))with an inline builder. A builder with no normalizer discards the response body (the handler returns{ data: null }) — callers needing it useajaxdirectly, asUserBadge#revokedoes. - Optimistic updates:
store.push({ data: { type, id: String(id), attributes } }), thenthis._adoptResource(this.id)so a draft wrapper sees the new value; push the previous attributes back if the request rejects (UserBadge#favorite).
Plugin-extension APIs (api.addModelField/Getter/Method/…) still work — fields land as tracked properties on the wrapper, not in the cache. Schema-contributed plugin fields are planned but not built — don't design anything that depends on them.
Changing a converted model
- New server field: add one line to the schema (
attrs(...)) —resourceFrompicks it up automatically. - New client-only field: also declare it in the schema (cheap, and keeps reads legal); mark it with a comment saying who sets it.
- New relationship: schema
belongsTo+ normalizermaybeRelate+ push the related resource intoincluded. Only between migrated types. - New endpoint: add a builder; CRUD shapes use
builders/helpers.js, RPC shapes are inline objects. - Derived values: plain getters on the model class — define them before
defineFieldForwardersruns. It skips any name that resolves anywhere on the prototype chain, which is also what stops a legacy-derived schema field calledsave/get/destroyfrom shadowing a base method. - Prefer data-layer fixes (normalizer, schema, builder, compat layer) over touching consumers (routes, controllers, components) — the migration's goal is unchanged call sites.
- Shedding
RestCompatModelfor a model is the end state: only after no caller usesget/set/store.createRecord/legacysave.