@iamjulianacosta/mobx-data 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +366 -0
- package/dist/CacheHandler-BTU_rYkv.js +208 -0
- package/dist/CacheHandler-BTU_rYkv.js.map +1 -0
- package/dist/CacheHandler-CXgY9IJo.cjs +2 -0
- package/dist/CacheHandler-CXgY9IJo.cjs.map +1 -0
- package/dist/EmbeddedRecordsMixin-CBvqNdgC.cjs +2 -0
- package/dist/EmbeddedRecordsMixin-CBvqNdgC.cjs.map +1 -0
- package/dist/EmbeddedRecordsMixin-VoHluHCT.js +261 -0
- package/dist/EmbeddedRecordsMixin-VoHluHCT.js.map +1 -0
- package/dist/JsonApiSerializer-CC5HXp4b.js +194 -0
- package/dist/JsonApiSerializer-CC5HXp4b.js.map +1 -0
- package/dist/JsonApiSerializer-CKB02AgP.cjs +2 -0
- package/dist/JsonApiSerializer-CKB02AgP.cjs.map +1 -0
- package/dist/MemoryAdapter-Bx1e7ndV.js +123 -0
- package/dist/MemoryAdapter-Bx1e7ndV.js.map +1 -0
- package/dist/MemoryAdapter-D1cTyydm.cjs +2 -0
- package/dist/MemoryAdapter-D1cTyydm.cjs.map +1 -0
- package/dist/ODataAdapter-C4IHK4BK.js +157 -0
- package/dist/ODataAdapter-C4IHK4BK.js.map +1 -0
- package/dist/ODataAdapter-DyyF1sdA.cjs +2 -0
- package/dist/ODataAdapter-DyyF1sdA.cjs.map +1 -0
- package/dist/RestAdapter-B4aRvs4m.js +355 -0
- package/dist/RestAdapter-B4aRvs4m.js.map +1 -0
- package/dist/RestAdapter-CJOwTsKK.cjs +2 -0
- package/dist/RestAdapter-CJOwTsKK.cjs.map +1 -0
- package/dist/SchemaService-DZwkFgZu.js +102 -0
- package/dist/SchemaService-DZwkFgZu.js.map +1 -0
- package/dist/SchemaService-Di_yjVzU.cjs +2 -0
- package/dist/SchemaService-Di_yjVzU.cjs.map +1 -0
- package/dist/Serializer-95gi5edy.cjs +2 -0
- package/dist/Serializer-95gi5edy.cjs.map +1 -0
- package/dist/Serializer-FxJbsZ50.js +139 -0
- package/dist/Serializer-FxJbsZ50.js.map +1 -0
- package/dist/Store-BdwMrbDi.cjs +2 -0
- package/dist/Store-BdwMrbDi.cjs.map +1 -0
- package/dist/Store-CZ7Z-Nme.js +912 -0
- package/dist/Store-CZ7Z-Nme.js.map +1 -0
- package/dist/adapter/Adapter.d.ts +146 -0
- package/dist/adapter/Adapter.d.ts.map +1 -0
- package/dist/adapter/MemoryAdapter.d.ts +44 -0
- package/dist/adapter/MemoryAdapter.d.ts.map +1 -0
- package/dist/adapter/RestAdapter.d.ts +57 -0
- package/dist/adapter/RestAdapter.d.ts.map +1 -0
- package/dist/adapter/index.cjs +2 -0
- package/dist/adapter/index.cjs.map +1 -0
- package/dist/adapter/index.d.ts +4 -0
- package/dist/adapter/index.d.ts.map +1 -0
- package/dist/adapter/index.js +8 -0
- package/dist/adapter/index.js.map +1 -0
- package/dist/date-Bj4O2W1F.js +107 -0
- package/dist/date-Bj4O2W1F.js.map +1 -0
- package/dist/date-CRCe-9gf.cjs +2 -0
- package/dist/date-CRCe-9gf.cjs.map +1 -0
- package/dist/decorators-HQ1KnRdh.cjs +2 -0
- package/dist/decorators-HQ1KnRdh.cjs.map +1 -0
- package/dist/decorators-Zr35qr6A.js +50 -0
- package/dist/decorators-Zr35qr6A.js.map +1 -0
- package/dist/index.cjs +2 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +52 -0
- package/dist/index.js.map +1 -0
- package/dist/json-api/JsonApiAdapter.d.ts +38 -0
- package/dist/json-api/JsonApiAdapter.d.ts.map +1 -0
- package/dist/json-api/JsonApiSerializer.d.ts +73 -0
- package/dist/json-api/JsonApiSerializer.d.ts.map +1 -0
- package/dist/json-api/index.cjs +2 -0
- package/dist/json-api/index.cjs.map +1 -0
- package/dist/json-api/index.d.ts +3 -0
- package/dist/json-api/index.d.ts.map +1 -0
- package/dist/json-api/index.js +6 -0
- package/dist/json-api/index.js.map +1 -0
- package/dist/model/Errors.d.ts +46 -0
- package/dist/model/Errors.d.ts.map +1 -0
- package/dist/model/Model.d.ts +226 -0
- package/dist/model/Model.d.ts.map +1 -0
- package/dist/model/Snapshot.d.ts +72 -0
- package/dist/model/Snapshot.d.ts.map +1 -0
- package/dist/model/StateMachine.d.ts +45 -0
- package/dist/model/StateMachine.d.ts.map +1 -0
- package/dist/model/index.cjs +2 -0
- package/dist/model/index.cjs.map +1 -0
- package/dist/model/index.d.ts +6 -0
- package/dist/model/index.d.ts.map +1 -0
- package/dist/model/index.js +11 -0
- package/dist/model/index.js.map +1 -0
- package/dist/model/relationships.d.ts +182 -0
- package/dist/model/relationships.d.ts.map +1 -0
- package/dist/odata/ODataAdapter.d.ts +67 -0
- package/dist/odata/ODataAdapter.d.ts.map +1 -0
- package/dist/odata/index.cjs +2 -0
- package/dist/odata/index.cjs.map +1 -0
- package/dist/odata/index.d.ts +2 -0
- package/dist/odata/index.d.ts.map +1 -0
- package/dist/odata/index.js +5 -0
- package/dist/odata/index.js.map +1 -0
- package/dist/relationships-B55LBaCW.cjs +2 -0
- package/dist/relationships-B55LBaCW.cjs.map +1 -0
- package/dist/relationships-BEXANmWg.js +821 -0
- package/dist/relationships-BEXANmWg.js.map +1 -0
- package/dist/request/CacheHandler.d.ts +50 -0
- package/dist/request/CacheHandler.d.ts.map +1 -0
- package/dist/request/FetchHandler.d.ts +41 -0
- package/dist/request/FetchHandler.d.ts.map +1 -0
- package/dist/request/RequestManager.d.ts +52 -0
- package/dist/request/RequestManager.d.ts.map +1 -0
- package/dist/request/index.cjs +2 -0
- package/dist/request/index.cjs.map +1 -0
- package/dist/request/index.d.ts +5 -0
- package/dist/request/index.d.ts.map +1 -0
- package/dist/request/index.js +7 -0
- package/dist/request/index.js.map +1 -0
- package/dist/request/types.d.ts +111 -0
- package/dist/request/types.d.ts.map +1 -0
- package/dist/schema/SchemaService.d.ts +58 -0
- package/dist/schema/SchemaService.d.ts.map +1 -0
- package/dist/schema/decorators.d.ts +50 -0
- package/dist/schema/decorators.d.ts.map +1 -0
- package/dist/schema/index.cjs +2 -0
- package/dist/schema/index.cjs.map +1 -0
- package/dist/schema/index.d.ts +4 -0
- package/dist/schema/index.d.ts.map +1 -0
- package/dist/schema/index.js +13 -0
- package/dist/schema/index.js.map +1 -0
- package/dist/schema/types.d.ts +61 -0
- package/dist/schema/types.d.ts.map +1 -0
- package/dist/serializer/EmbeddedRecordsMixin.d.ts +80 -0
- package/dist/serializer/EmbeddedRecordsMixin.d.ts.map +1 -0
- package/dist/serializer/JsonSerializer.d.ts +52 -0
- package/dist/serializer/JsonSerializer.d.ts.map +1 -0
- package/dist/serializer/RestSerializer.d.ts +43 -0
- package/dist/serializer/RestSerializer.d.ts.map +1 -0
- package/dist/serializer/Serializer.d.ts +202 -0
- package/dist/serializer/Serializer.d.ts.map +1 -0
- package/dist/serializer/index.cjs +2 -0
- package/dist/serializer/index.cjs.map +1 -0
- package/dist/serializer/index.d.ts +5 -0
- package/dist/serializer/index.d.ts.map +1 -0
- package/dist/serializer/index.js +9 -0
- package/dist/serializer/index.js.map +1 -0
- package/dist/store/IdentityMap.d.ts +53 -0
- package/dist/store/IdentityMap.d.ts.map +1 -0
- package/dist/store/RecordArray.d.ts +114 -0
- package/dist/store/RecordArray.d.ts.map +1 -0
- package/dist/store/Store.d.ts +395 -0
- package/dist/store/Store.d.ts.map +1 -0
- package/dist/store/index.cjs +2 -0
- package/dist/store/index.cjs.map +1 -0
- package/dist/store/index.d.ts +5 -0
- package/dist/store/index.d.ts.map +1 -0
- package/dist/store/index.js +8 -0
- package/dist/store/index.js.map +1 -0
- package/dist/transforms/Transform.d.ts +49 -0
- package/dist/transforms/Transform.d.ts.map +1 -0
- package/dist/transforms/boolean.d.ts +26 -0
- package/dist/transforms/boolean.d.ts.map +1 -0
- package/dist/transforms/date.d.ts +22 -0
- package/dist/transforms/date.d.ts.map +1 -0
- package/dist/transforms/index.cjs +2 -0
- package/dist/transforms/index.cjs.map +1 -0
- package/dist/transforms/index.d.ts +6 -0
- package/dist/transforms/index.d.ts.map +1 -0
- package/dist/transforms/index.js +9 -0
- package/dist/transforms/index.js.map +1 -0
- package/dist/transforms/number.d.ts +17 -0
- package/dist/transforms/number.d.ts.map +1 -0
- package/dist/transforms/string.d.ts +18 -0
- package/dist/transforms/string.d.ts.map +1 -0
- package/dist/types-C9NB2gRj.js +7 -0
- package/dist/types-C9NB2gRj.js.map +1 -0
- package/dist/types-uWOXMPWW.cjs +2 -0
- package/dist/types-uWOXMPWW.cjs.map +1 -0
- package/package.json +140 -0
- package/src/adapter/Adapter.ts +320 -0
- package/src/adapter/MemoryAdapter.ts +216 -0
- package/src/adapter/RestAdapter.ts +248 -0
- package/src/adapter/index.ts +7 -0
- package/src/index.ts +17 -0
- package/src/json-api/JsonApiAdapter.ts +93 -0
- package/src/json-api/JsonApiSerializer.ts +245 -0
- package/src/json-api/index.ts +2 -0
- package/src/model/Errors.ts +100 -0
- package/src/model/Model.ts +683 -0
- package/src/model/Snapshot.ts +162 -0
- package/src/model/StateMachine.ts +149 -0
- package/src/model/index.ts +20 -0
- package/src/model/relationships.ts +484 -0
- package/src/odata/ODataAdapter.ts +245 -0
- package/src/odata/index.ts +1 -0
- package/src/request/CacheHandler.ts +125 -0
- package/src/request/FetchHandler.ts +119 -0
- package/src/request/RequestManager.ts +112 -0
- package/src/request/index.ts +4 -0
- package/src/request/types.ts +139 -0
- package/src/schema/SchemaService.ts +161 -0
- package/src/schema/decorators.ts +162 -0
- package/src/schema/index.ts +3 -0
- package/src/schema/types.ts +66 -0
- package/src/serializer/EmbeddedRecordsMixin.ts +257 -0
- package/src/serializer/JsonSerializer.ts +173 -0
- package/src/serializer/RestSerializer.ts +138 -0
- package/src/serializer/Serializer.ts +397 -0
- package/src/serializer/index.ts +15 -0
- package/src/store/IdentityMap.ts +110 -0
- package/src/store/RecordArray.ts +210 -0
- package/src/store/Store.ts +1391 -0
- package/src/store/index.ts +11 -0
- package/src/transforms/Transform.ts +52 -0
- package/src/transforms/boolean.ts +57 -0
- package/src/transforms/date.ts +48 -0
- package/src/transforms/index.ts +5 -0
- package/src/transforms/number.ts +42 -0
- package/src/transforms/string.ts +35 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"EmbeddedRecordsMixin-CBvqNdgC.cjs","sources":["../src/serializer/JsonSerializer.ts","../src/serializer/RestSerializer.ts","../src/serializer/EmbeddedRecordsMixin.ts"],"sourcesContent":["/**\n * Flat-JSON serializer for simple REST APIs.\n *\n * `JsonSerializer` expects payloads to be plain JSON objects or arrays with\n * no root-key wrapping. It is the lowest-level concrete serializer and the\n * base that `RestSerializer` extends.\n *\n * Normalization:\n * - Array payload → `{ data: [NormalizedResource, …] }`\n * - Object payload → `{ data: NormalizedResource }`\n * - `null` / `undefined` → `{ data: null }`\n *\n * Serialization:\n * - Iterates `@attr` → writes via `serializeAttribute`\n * - Iterates `@belongsTo` / `@hasMany` → writes via `serializeBelongsTo` /\n * `serializeHasMany`\n *\n * `normalizeResponse` automatically dispatches to the correct per-operation\n * hook (`normalizeFindRecordResponse`, etc.) when a subclass overrides them.\n * If no override exists it falls through to `_buildDocument`.\n */\n\nimport { injectable } from 'tsyringe';\nimport {\n Serializer,\n type ModelClassMeta,\n type NormalizeRequestType,\n type NormalizedDocument,\n type NormalizedResource,\n type SerializerSnapshot,\n} from './Serializer.js';\n\n@injectable()\nexport class JsonSerializer extends Serializer {\n static dispatchMethodName(\n requestType: NormalizeRequestType,\n ): keyof Serializer | null {\n switch (requestType) {\n case 'findRecord':\n return 'normalizeFindRecordResponse';\n case 'findAll':\n return 'normalizeFindAllResponse';\n case 'query':\n return 'normalizeQueryResponse';\n case 'queryRecord':\n return 'normalizeQueryRecordResponse';\n case 'createRecord':\n return 'normalizeCreateRecordResponse';\n case 'updateRecord':\n return 'normalizeUpdateRecordResponse';\n case 'deleteRecord':\n return 'normalizeDeleteRecordResponse';\n default:\n return null;\n }\n }\n\n /**\n * Normalizes a single flat JSON object into a `NormalizedResource`.\n * Returns `null` for absent or non-object payloads.\n */\n override normalize(\n _store: unknown,\n modelClass: ModelClassMeta,\n payload: unknown,\n _prop?: string,\n ): NormalizedResource | null {\n if (payload === null || payload === undefined) {\n return null;\n }\n if (typeof payload !== 'object') {\n return null;\n }\n const hash = payload as Record<string, unknown>;\n const id = this.extractId(modelClass, hash);\n const attributes = this.extractAttributes(modelClass, hash);\n const relationships = this.extractRelationships(modelClass, hash);\n\n const resource: NormalizedResource = {\n type: modelClass.modelName,\n id,\n attributes,\n };\n if (relationships && Object.keys(relationships).length > 0) {\n resource.relationships = relationships;\n }\n return resource;\n }\n\n /**\n * Entry point for normalization.\n *\n * Checks whether a subclass has overridden the relevant per-operation hook\n * (e.g. `normalizeFindRecordResponse`). If so, calls it; otherwise falls\n * through to `_buildDocument`.\n */\n override normalizeResponse(\n store: unknown,\n modelClass: ModelClassMeta,\n payload: unknown,\n id: string | null,\n requestType: NormalizeRequestType,\n ): NormalizedDocument {\n const methodName = JsonSerializer.dispatchMethodName(requestType);\n if (methodName) {\n const override = (this as unknown as Record<string, unknown>)[methodName];\n const baseImpl = (Serializer.prototype as unknown as Record<string, unknown>)[\n methodName\n ];\n if (typeof override === 'function' && override !== baseImpl) {\n return (override as (...args: unknown[]) => NormalizedDocument).call(\n this,\n store,\n modelClass,\n payload,\n id,\n requestType,\n );\n }\n }\n return this._buildDocument(store, modelClass, payload, id, requestType);\n }\n\n /**\n * Builds a `NormalizedDocument` from a raw payload.\n * Arrays are normalized item by item; plain objects are normalized as a\n * single resource.\n */\n protected _buildDocument(\n store: unknown,\n modelClass: ModelClassMeta,\n payload: unknown,\n _id: string | null,\n _requestType: NormalizeRequestType,\n ): NormalizedDocument {\n if (payload === null || payload === undefined) {\n return { data: null };\n }\n if (Array.isArray(payload)) {\n const data = payload\n .map((p) => this.normalize(store, modelClass, p))\n .filter((r): r is NormalizedResource => r !== null);\n return { data };\n }\n const data = this.normalize(store, modelClass, payload);\n return { data };\n }\n\n /**\n * Serializes a snapshot to a flat JSON object.\n * Includes `id` when `options.includeId` is `true`.\n */\n override serialize(\n snapshot: SerializerSnapshot,\n options?: { includeId?: boolean },\n ): Record<string, unknown> {\n const json: Record<string, unknown> = {};\n if (options?.includeId && snapshot.id !== null) {\n json[this.primaryKey] = snapshot.id;\n }\n snapshot.eachAttribute((key, meta) => {\n this.serializeAttribute(snapshot, json, key, meta);\n });\n snapshot.eachRelationship((_key, rel) => {\n if (rel.kind === 'belongsTo') {\n this.serializeBelongsTo(snapshot, json, rel);\n } else {\n this.serializeHasMany(snapshot, json, rel);\n }\n });\n return json;\n }\n}\n","/**\n * REST serializer for root-key payloads with optional sideloading.\n *\n * `RestSerializer` expects the primary data to be wrapped under a root key\n * that matches either the singular or plural model name:\n *\n * ```json\n * { \"post\": { \"id\": \"1\", \"title\": \"Hello\" } }\n * { \"posts\": [{ \"id\": \"1\", … }, { \"id\": \"2\", … }] }\n * ```\n *\n * Any additional keys in the payload are treated as sideloaded (compound)\n * data. `meta` and `links` keys are reserved and forwarded to the document.\n *\n * Sideloaded types are inferred from the payload key via `modelNameFromPayloadKey`\n * (default: singularization).\n *\n * Extends `JsonSerializer` so it inherits flat `normalize` and `serialize`\n * behaviour and only overrides document-level parsing via `_buildDocument`.\n */\n\nimport { injectable } from 'tsyringe';\nimport pluralize from 'pluralize';\nimport {\n type ModelClassMeta,\n type NormalizeRequestType,\n type NormalizedDocument,\n type NormalizedResource,\n} from './Serializer.js';\nimport { JsonSerializer } from './JsonSerializer.js';\n\n@injectable()\nexport class RestSerializer extends JsonSerializer {\n /**\n * Returns the plural payload key for a model name.\n * e.g. `'post'` → `'posts'`\n */\n payloadKeyFromModelName(modelName: string): string {\n return pluralize.plural(modelName);\n }\n\n /**\n * Returns the model name for a payload root key.\n * e.g. `'posts'` → `'post'`\n */\n modelNameFromPayloadKey(key: string): string {\n return pluralize.singular(key);\n }\n\n /**\n * Builds a `NormalizedDocument` from a root-key REST payload.\n *\n * - Looks for the model data under the singular or plural root key.\n * - Treats every other non-reserved key as a sideloaded type.\n * - Preserves `meta` and `links` from the root.\n */\n protected override _buildDocument(\n store: unknown,\n modelClass: ModelClassMeta,\n payload: unknown,\n _id: string | null,\n _requestType: NormalizeRequestType,\n ): NormalizedDocument {\n if (payload === null || payload === undefined || typeof payload !== 'object') {\n return { data: null };\n }\n const hash = payload as Record<string, unknown>;\n const singular = modelClass.modelName;\n const plural = this.payloadKeyFromModelName(singular);\n\n let data: NormalizedResource | NormalizedResource[] | null = null;\n const primaryKeys = new Set<string>();\n\n if (singular in hash) {\n primaryKeys.add(singular);\n const raw = hash[singular];\n if (Array.isArray(raw)) {\n data = raw\n .map((entry) => this.normalize(store, modelClass, entry))\n .filter((resource): resource is NormalizedResource => resource !== null);\n } else {\n data = this.normalize(store, modelClass, raw);\n }\n } else if (plural in hash) {\n primaryKeys.add(plural);\n const raw = hash[plural];\n if (Array.isArray(raw)) {\n data = raw\n .map((entry) => this.normalize(store, modelClass, entry))\n .filter((resource): resource is NormalizedResource => resource !== null);\n } else {\n data = this.normalize(store, modelClass, raw);\n }\n }\n\n // Collect sideloaded records from all remaining root keys.\n const included: NormalizedResource[] = [];\n for (const [key, value] of Object.entries(hash)) {\n if (primaryKeys.has(key)) {\n continue;\n }\n if (key === 'meta' || key === 'links') {\n continue;\n }\n const sideloadType = this.modelNameFromPayloadKey(key);\n const sideloadClass: ModelClassMeta = {\n modelName: sideloadType,\n attributes: new Map(),\n relationships: new Map(),\n };\n if (Array.isArray(value)) {\n for (const item of value) {\n const normalized = this.normalize(store, sideloadClass, item);\n if (normalized) {\n included.push(normalized);\n }\n }\n } else if (value && typeof value === 'object') {\n const normalized = this.normalize(store, sideloadClass, value);\n if (normalized) {\n included.push(normalized);\n }\n }\n }\n\n const doc: NormalizedDocument = { data };\n if (included.length > 0) {\n doc.included = included;\n }\n if (hash.meta && typeof hash.meta === 'object') {\n doc.meta = hash.meta as Record<string, unknown>;\n }\n if (hash.links && typeof hash.links === 'object') {\n doc.links = hash.links as Record<string, string>;\n }\n return doc;\n }\n}\n","/**\n * Mixin that adds support for embedded (nested) records in REST payloads.\n *\n * Apply with:\n * ```ts\n * class PostSerializer extends EmbeddedRecordsMixin(RestSerializer) {\n * attrs = {\n * comments: { embedded: 'always' },\n * author: { embedded: 'always', serialize: 'records' },\n * };\n * }\n * ```\n *\n * ## How it works\n *\n * ### Deserialization\n * When `embedded: 'always'` is set for a relationship, `normalize()` intercepts\n * the raw payload before passing it to `super.normalize()`:\n * - For `hasMany`: replaces the nested array with a plain id array and queues\n * each nested object as an `included` resource.\n * - For `belongsTo`: replaces the nested object with the extracted id and\n * queues the nested object as an `included` resource.\n *\n * Queued resources are collected during `normalizeResponse()` and appended to\n * `document.included` so the `Store` can push them into the identity map.\n *\n * ### Serialization\n * When `serialize: 'records'` is set, `serializeHasMany` / `serializeBelongsTo`\n * write the full related record(s) into the payload instead of just ids.\n *\n * ## Configuration\n *\n * Each entry in `attrs` is an `EmbeddedAttrConfig`:\n * - `embedded: 'always'` — enable embedded deserialization.\n * - `serialize: 'records'` — write full records on serialize.\n * - `serialize: 'ids'` — write id array on serialize (default).\n * - `serialize: false` — omit relationship from serialized payload.\n * - `deserialize: 'records'` — same as `embedded: 'always'`.\n * - `deserialize: false` — ignore this relationship during normalization.\n */\n\nimport type { RelationshipDef } from '@mobx-data/schema';\nimport type {\n ModelClassMeta,\n NormalizeRequestType,\n NormalizedDocument,\n NormalizedResource,\n SerializerSnapshot,\n} from './Serializer.js';\n\n/** Per-relationship embedding configuration. */\nexport interface EmbeddedAttrConfig {\n /** `'always'` to deserialize embedded records; `'never'` to skip. */\n embedded?: 'always' | 'never';\n /** `'records'` to serialize full objects; `'ids'` for ids only; `false` to omit. */\n serialize?: 'records' | 'ids' | false;\n /** `'records'` to deserialize embedded objects; `'ids'` for plain ids; `false` to skip. */\n deserialize?: 'records' | 'ids' | false;\n}\n\n/** Map of relationship name → embedding config. */\nexport interface EmbeddedRecordsAttrs {\n [key: string]: EmbeddedAttrConfig;\n}\n\n/**\n * The minimal serializer interface required by the mixin.\n * Any class extending `JsonSerializer` satisfies this.\n */\nexport interface JsonSerializerLike {\n attrs?: EmbeddedRecordsAttrs;\n primaryKey: string;\n normalize(\n store: unknown,\n modelClass: ModelClassMeta,\n payload: unknown,\n prop?: string,\n ): NormalizedResource | null;\n normalizeResponse(\n store: unknown,\n modelClass: ModelClassMeta,\n payload: unknown,\n id: string | null,\n requestType: NormalizeRequestType,\n ): NormalizedDocument;\n serialize(\n snapshot: SerializerSnapshot,\n options?: { includeId?: boolean },\n ): Record<string, unknown>;\n serializeHasMany(\n snapshot: SerializerSnapshot,\n json: Record<string, unknown>,\n relationship: RelationshipDef,\n ): void;\n serializeBelongsTo(\n snapshot: SerializerSnapshot,\n json: Record<string, unknown>,\n relationship: RelationshipDef,\n ): void;\n keyForAttribute(key: string): string;\n keyForRelationship(key: string): string;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype Constructor<T> = new (...args: any[]) => T;\n\n/**\n * Returns a new class that extends `Base` with embedded-record support.\n * `Base` must be (or extend) `JsonSerializer`.\n */\nexport function EmbeddedRecordsMixin<\n TBase extends Constructor<JsonSerializerLike>,\n>(Base: TBase): TBase {\n class WithEmbeddedRecords extends Base {\n override attrs?: EmbeddedRecordsAttrs;\n\n /** Accumulates extracted embedded resources during a `normalizeResponse` call. */\n private pendingIncluded: NormalizedResource[] = [];\n\n /**\n * Intercepts raw payload hashes to extract embedded records.\n *\n * For each relationship configured with `embedded: 'always'`:\n * - Recursively normalizes the embedded object(s) and adds them to\n * `pendingIncluded`.\n * - Replaces the embedded value in the hash with the extracted id(s) so\n * `super.normalize` treats it as a plain id reference.\n */\n override normalize(\n store: unknown,\n modelClass: ModelClassMeta,\n payload: unknown,\n prop?: string,\n ): NormalizedResource | null {\n if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {\n return super.normalize(store, modelClass, payload, prop);\n }\n const src = payload as Record<string, unknown>;\n const attrs = this.attrs ?? {};\n const hash: Record<string, unknown> = { ...src };\n\n for (const [name, rel] of modelClass.relationships) {\n const cfg = attrs[name];\n if (!cfg || cfg.embedded !== 'always') {\n continue;\n }\n const raw = hash[name];\n if (raw === undefined || raw === null) {\n continue;\n }\n\n if (rel.kind === 'hasMany' && Array.isArray(raw)) {\n const ids: string[] = [];\n for (const item of raw) {\n const extracted = this.extractEmbeddedResource(store, rel, item);\n if (extracted && extracted.id !== null) {\n ids.push(extracted.id);\n this.pendingIncluded.push(extracted);\n }\n }\n hash[name] = ids;\n } else if (\n rel.kind === 'belongsTo'\n && typeof raw === 'object'\n && !Array.isArray(raw)\n ) {\n const extracted = this.extractEmbeddedResource(store, rel, raw);\n if (extracted && extracted.id !== null) {\n this.pendingIncluded.push(extracted);\n hash[name] = extracted.id;\n }\n }\n }\n\n return super.normalize(store, modelClass, hash, prop);\n }\n\n /**\n * Resets `pendingIncluded`, delegates to `super.normalizeResponse`, then\n * appends any extracted embedded resources to `document.included`.\n */\n override normalizeResponse(\n store: unknown,\n modelClass: ModelClassMeta,\n payload: unknown,\n id: string | null,\n requestType: NormalizeRequestType,\n ): NormalizedDocument {\n this.pendingIncluded = [];\n const doc = super.normalizeResponse(store, modelClass, payload, id, requestType);\n if (this.pendingIncluded.length > 0) {\n const included = doc.included ? [...doc.included] : [];\n included.push(...this.pendingIncluded);\n doc.included = included;\n this.pendingIncluded = [];\n }\n return doc;\n }\n\n /**\n * When `serialize: 'records'` is configured, writes the full related\n * record objects instead of just ids.\n */\n override serializeHasMany(\n snapshot: SerializerSnapshot,\n json: Record<string, unknown>,\n relationship: RelationshipDef,\n ): void {\n const cfg = this.attrs?.[relationship.name];\n if (cfg?.serialize === 'records') {\n const records = snapshot.hasMany(relationship.name) as unknown[];\n json[this.keyForRelationship(relationship.name)] = records ?? [];\n return;\n }\n super.serializeHasMany(snapshot, json, relationship);\n }\n\n /**\n * When `serialize: 'records'` is configured, writes the full related\n * record object instead of just the id.\n */\n override serializeBelongsTo(\n snapshot: SerializerSnapshot,\n json: Record<string, unknown>,\n relationship: RelationshipDef,\n ): void {\n const cfg = this.attrs?.[relationship.name];\n if (cfg?.serialize === 'records') {\n const record = snapshot.belongsTo(relationship.name);\n json[this.keyForRelationship(relationship.name)] = record ?? null;\n return;\n }\n super.serializeBelongsTo(snapshot, json, relationship);\n }\n\n /**\n * Normalizes a single embedded resource object using the related model's\n * type as a placeholder `ModelClassMeta`.\n */\n private extractEmbeddedResource(\n store: unknown,\n rel: RelationshipDef,\n item: unknown,\n ): NormalizedResource | null {\n if (!item || typeof item !== 'object' || Array.isArray(item)) {\n return null;\n }\n const embeddedClass: ModelClassMeta = {\n modelName: rel.type,\n attributes: new Map(),\n relationships: new Map(),\n };\n return this.normalize(store, embeddedClass, item);\n }\n }\n return WithEmbeddedRecords as unknown as TBase;\n}\n"],"names":["JsonSerializer","Serializer","requestType","_store","modelClass","payload","_prop","hash","id","attributes","relationships","resource","store","methodName","override","baseImpl","_id","_requestType","p","r","data","snapshot","options","json","key","meta","_key","rel","__decorateClass","injectable","RestSerializer","modelName","pluralize","singular","plural","primaryKeys","raw","entry","included","value","sideloadClass","item","normalized","doc","EmbeddedRecordsMixin","Base","WithEmbeddedRecords","prop","src","attrs","name","cfg","ids","extracted","relationship","_a","records","record","embeddedClass"],"mappings":"mPAiCaA,QAAAA,eAAN,cAA6BC,EAAAA,UAAW,CAC7C,OAAO,mBACLC,EACyB,CACzB,OAAQA,EAAA,CACN,IAAK,aACH,MAAO,8BACT,IAAK,UACH,MAAO,2BACT,IAAK,QACH,MAAO,yBACT,IAAK,cACH,MAAO,+BACT,IAAK,eACH,MAAO,gCACT,IAAK,eACH,MAAO,gCACT,IAAK,eACH,MAAO,gCACT,QACE,OAAO,IAAA,CAEb,CAMS,UACPC,EACAC,EACAC,EACAC,EAC2B,CAI3B,GAHID,GAAY,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C,IAAIH,GAAA,YAAAA,EAAK,aAAc,UAAW,CAChC,MAAMK,EAAUnC,EAAS,QAAQiC,EAAa,IAAI,EAClD/B,EAAK,KAAK,mBAAmB+B,EAAa,IAAI,CAAC,EAAIE,GAAW,CAAA,EAC9D,MACF,CACA,MAAM,iBAAiBnC,EAAUE,EAAM+B,CAAY,CACrD,CAMS,mBACPjC,EACAE,EACA+B,EACM,OACN,MAAMH,GAAMI,EAAA,KAAK,QAAL,YAAAA,EAAaD,EAAa,MACtC,IAAIH,GAAA,YAAAA,EAAK,aAAc,UAAW,CAChC,MAAMM,EAASpC,EAAS,UAAUiC,EAAa,IAAI,EACnD/B,EAAK,KAAK,mBAAmB+B,EAAa,IAAI,CAAC,EAAIG,GAAU,KAC7D,MACF,CACA,MAAM,mBAAmBpC,EAAUE,EAAM+B,CAAY,CACvD,CAMQ,wBACN1C,EACAe,EACAc,EAC2B,CAC3B,GAAI,CAACA,GAAQ,OAAOA,GAAS,UAAY,MAAM,QAAQA,CAAI,EACzD,OAAO,KAET,MAAMiB,EAAgC,CACpC,UAAW/B,EAAI,KACf,eAAgB,IAChB,kBAAmB,GAAI,EAEzB,OAAO,KAAK,UAAUf,EAAO8C,EAAejB,CAAI,CAClD,CAAA,CAEF,OAAOK,CACT"}
|
|
@@ -0,0 +1,261 @@
|
|
|
1
|
+
import { injectable as _ } from "tsyringe";
|
|
2
|
+
import R from "pluralize";
|
|
3
|
+
import { S as g } from "./Serializer-FxJbsZ50.js";
|
|
4
|
+
var v = Object.getOwnPropertyDescriptor, w = (t, a, i, s) => {
|
|
5
|
+
for (var r = s > 1 ? void 0 : s ? v(a, i) : a, e = t.length - 1, n; e >= 0; e--)
|
|
6
|
+
(n = t[e]) && (r = n(r) || r);
|
|
7
|
+
return r;
|
|
8
|
+
};
|
|
9
|
+
let z = class extends g {
|
|
10
|
+
static dispatchMethodName(t) {
|
|
11
|
+
switch (t) {
|
|
12
|
+
case "findRecord":
|
|
13
|
+
return "normalizeFindRecordResponse";
|
|
14
|
+
case "findAll":
|
|
15
|
+
return "normalizeFindAllResponse";
|
|
16
|
+
case "query":
|
|
17
|
+
return "normalizeQueryResponse";
|
|
18
|
+
case "queryRecord":
|
|
19
|
+
return "normalizeQueryRecordResponse";
|
|
20
|
+
case "createRecord":
|
|
21
|
+
return "normalizeCreateRecordResponse";
|
|
22
|
+
case "updateRecord":
|
|
23
|
+
return "normalizeUpdateRecordResponse";
|
|
24
|
+
case "deleteRecord":
|
|
25
|
+
return "normalizeDeleteRecordResponse";
|
|
26
|
+
default:
|
|
27
|
+
return null;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Normalizes a single flat JSON object into a `NormalizedResource`.
|
|
32
|
+
* Returns `null` for absent or non-object payloads.
|
|
33
|
+
*/
|
|
34
|
+
normalize(t, a, i, s) {
|
|
35
|
+
if (i == null || typeof i != "object")
|
|
36
|
+
return null;
|
|
37
|
+
const r = i, e = this.extractId(a, r), n = this.extractAttributes(a, r), o = this.extractRelationships(a, r), l = {
|
|
38
|
+
type: a.modelName,
|
|
39
|
+
id: e,
|
|
40
|
+
attributes: n
|
|
41
|
+
};
|
|
42
|
+
return o && Object.keys(o).length > 0 && (l.relationships = o), l;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Entry point for normalization.
|
|
46
|
+
*
|
|
47
|
+
* Checks whether a subclass has overridden the relevant per-operation hook
|
|
48
|
+
* (e.g. `normalizeFindRecordResponse`). If so, calls it; otherwise falls
|
|
49
|
+
* through to `_buildDocument`.
|
|
50
|
+
*/
|
|
51
|
+
normalizeResponse(t, a, i, s, r) {
|
|
52
|
+
const e = z.dispatchMethodName(r);
|
|
53
|
+
if (e) {
|
|
54
|
+
const n = this[e], o = g.prototype[e];
|
|
55
|
+
if (typeof n == "function" && n !== o)
|
|
56
|
+
return n.call(
|
|
57
|
+
this,
|
|
58
|
+
t,
|
|
59
|
+
a,
|
|
60
|
+
i,
|
|
61
|
+
s,
|
|
62
|
+
r
|
|
63
|
+
);
|
|
64
|
+
}
|
|
65
|
+
return this._buildDocument(t, a, i, s, r);
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Builds a `NormalizedDocument` from a raw payload.
|
|
69
|
+
* Arrays are normalized item by item; plain objects are normalized as a
|
|
70
|
+
* single resource.
|
|
71
|
+
*/
|
|
72
|
+
_buildDocument(t, a, i, s, r) {
|
|
73
|
+
return i == null ? { data: null } : Array.isArray(i) ? { data: i.map((o) => this.normalize(t, a, o)).filter((o) => o !== null) } : { data: this.normalize(t, a, i) };
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Serializes a snapshot to a flat JSON object.
|
|
77
|
+
* Includes `id` when `options.includeId` is `true`.
|
|
78
|
+
*/
|
|
79
|
+
serialize(t, a) {
|
|
80
|
+
const i = {};
|
|
81
|
+
return a != null && a.includeId && t.id !== null && (i[this.primaryKey] = t.id), t.eachAttribute((s, r) => {
|
|
82
|
+
this.serializeAttribute(t, i, s, r);
|
|
83
|
+
}), t.eachRelationship((s, r) => {
|
|
84
|
+
r.kind === "belongsTo" ? this.serializeBelongsTo(t, i, r) : this.serializeHasMany(t, i, r);
|
|
85
|
+
}), i;
|
|
86
|
+
}
|
|
87
|
+
};
|
|
88
|
+
z = w([
|
|
89
|
+
_()
|
|
90
|
+
], z);
|
|
91
|
+
var M = Object.getOwnPropertyDescriptor, x = (t, a, i, s) => {
|
|
92
|
+
for (var r = s > 1 ? void 0 : s ? M(a, i) : a, e = t.length - 1, n; e >= 0; e--)
|
|
93
|
+
(n = t[e]) && (r = n(r) || r);
|
|
94
|
+
return r;
|
|
95
|
+
};
|
|
96
|
+
let A = class extends z {
|
|
97
|
+
/**
|
|
98
|
+
* Returns the plural payload key for a model name.
|
|
99
|
+
* e.g. `'post'` → `'posts'`
|
|
100
|
+
*/
|
|
101
|
+
payloadKeyFromModelName(t) {
|
|
102
|
+
return R.plural(t);
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* Returns the model name for a payload root key.
|
|
106
|
+
* e.g. `'posts'` → `'post'`
|
|
107
|
+
*/
|
|
108
|
+
modelNameFromPayloadKey(t) {
|
|
109
|
+
return R.singular(t);
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Builds a `NormalizedDocument` from a root-key REST payload.
|
|
113
|
+
*
|
|
114
|
+
* - Looks for the model data under the singular or plural root key.
|
|
115
|
+
* - Treats every other non-reserved key as a sideloaded type.
|
|
116
|
+
* - Preserves `meta` and `links` from the root.
|
|
117
|
+
*/
|
|
118
|
+
_buildDocument(t, a, i, s, r) {
|
|
119
|
+
if (i == null || typeof i != "object")
|
|
120
|
+
return { data: null };
|
|
121
|
+
const e = i, n = a.modelName, o = this.payloadKeyFromModelName(n);
|
|
122
|
+
let l = null;
|
|
123
|
+
const u = /* @__PURE__ */ new Set();
|
|
124
|
+
if (n in e) {
|
|
125
|
+
u.add(n);
|
|
126
|
+
const d = e[n];
|
|
127
|
+
Array.isArray(d) ? l = d.map((c) => this.normalize(t, a, c)).filter((c) => c !== null) : l = this.normalize(t, a, d);
|
|
128
|
+
} else if (o in e) {
|
|
129
|
+
u.add(o);
|
|
130
|
+
const d = e[o];
|
|
131
|
+
Array.isArray(d) ? l = d.map((c) => this.normalize(t, a, c)).filter((c) => c !== null) : l = this.normalize(t, a, d);
|
|
132
|
+
}
|
|
133
|
+
const m = [];
|
|
134
|
+
for (const [d, c] of Object.entries(e)) {
|
|
135
|
+
if (u.has(d) || d === "meta" || d === "links")
|
|
136
|
+
continue;
|
|
137
|
+
const y = {
|
|
138
|
+
modelName: this.modelNameFromPayloadKey(d),
|
|
139
|
+
attributes: /* @__PURE__ */ new Map(),
|
|
140
|
+
relationships: /* @__PURE__ */ new Map()
|
|
141
|
+
};
|
|
142
|
+
if (Array.isArray(c))
|
|
143
|
+
for (const h of c) {
|
|
144
|
+
const b = this.normalize(t, y, h);
|
|
145
|
+
b && m.push(b);
|
|
146
|
+
}
|
|
147
|
+
else if (c && typeof c == "object") {
|
|
148
|
+
const h = this.normalize(t, y, c);
|
|
149
|
+
h && m.push(h);
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
const f = { data: l };
|
|
153
|
+
return m.length > 0 && (f.included = m), e.meta && typeof e.meta == "object" && (f.meta = e.meta), e.links && typeof e.links == "object" && (f.links = e.links), f;
|
|
154
|
+
}
|
|
155
|
+
};
|
|
156
|
+
A = x([
|
|
157
|
+
_()
|
|
158
|
+
], A);
|
|
159
|
+
function I(t) {
|
|
160
|
+
class a extends t {
|
|
161
|
+
constructor() {
|
|
162
|
+
super(...arguments), this.pendingIncluded = [];
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
165
|
+
* Intercepts raw payload hashes to extract embedded records.
|
|
166
|
+
*
|
|
167
|
+
* For each relationship configured with `embedded: 'always'`:
|
|
168
|
+
* - Recursively normalizes the embedded object(s) and adds them to
|
|
169
|
+
* `pendingIncluded`.
|
|
170
|
+
* - Replaces the embedded value in the hash with the extracted id(s) so
|
|
171
|
+
* `super.normalize` treats it as a plain id reference.
|
|
172
|
+
*/
|
|
173
|
+
normalize(s, r, e, n) {
|
|
174
|
+
if (!e || typeof e != "object" || Array.isArray(e))
|
|
175
|
+
return super.normalize(s, r, e, n);
|
|
176
|
+
const o = e, l = this.attrs ?? {}, u = { ...o };
|
|
177
|
+
for (const [m, f] of r.relationships) {
|
|
178
|
+
const d = l[m];
|
|
179
|
+
if (!d || d.embedded !== "always")
|
|
180
|
+
continue;
|
|
181
|
+
const c = u[m];
|
|
182
|
+
if (c != null) {
|
|
183
|
+
if (f.kind === "hasMany" && Array.isArray(c)) {
|
|
184
|
+
const p = [];
|
|
185
|
+
for (const y of c) {
|
|
186
|
+
const h = this.extractEmbeddedResource(s, f, y);
|
|
187
|
+
h && h.id !== null && (p.push(h.id), this.pendingIncluded.push(h));
|
|
188
|
+
}
|
|
189
|
+
u[m] = p;
|
|
190
|
+
} else if (f.kind === "belongsTo" && typeof c == "object" && !Array.isArray(c)) {
|
|
191
|
+
const p = this.extractEmbeddedResource(s, f, c);
|
|
192
|
+
p && p.id !== null && (this.pendingIncluded.push(p), u[m] = p.id);
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
return super.normalize(s, r, u, n);
|
|
197
|
+
}
|
|
198
|
+
/**
|
|
199
|
+
* Resets `pendingIncluded`, delegates to `super.normalizeResponse`, then
|
|
200
|
+
* appends any extracted embedded resources to `document.included`.
|
|
201
|
+
*/
|
|
202
|
+
normalizeResponse(s, r, e, n, o) {
|
|
203
|
+
this.pendingIncluded = [];
|
|
204
|
+
const l = super.normalizeResponse(s, r, e, n, o);
|
|
205
|
+
if (this.pendingIncluded.length > 0) {
|
|
206
|
+
const u = l.included ? [...l.included] : [];
|
|
207
|
+
u.push(...this.pendingIncluded), l.included = u, this.pendingIncluded = [];
|
|
208
|
+
}
|
|
209
|
+
return l;
|
|
210
|
+
}
|
|
211
|
+
/**
|
|
212
|
+
* When `serialize: 'records'` is configured, writes the full related
|
|
213
|
+
* record objects instead of just ids.
|
|
214
|
+
*/
|
|
215
|
+
serializeHasMany(s, r, e) {
|
|
216
|
+
var o;
|
|
217
|
+
const n = (o = this.attrs) == null ? void 0 : o[e.name];
|
|
218
|
+
if ((n == null ? void 0 : n.serialize) === "records") {
|
|
219
|
+
const l = s.hasMany(e.name);
|
|
220
|
+
r[this.keyForRelationship(e.name)] = l ?? [];
|
|
221
|
+
return;
|
|
222
|
+
}
|
|
223
|
+
super.serializeHasMany(s, r, e);
|
|
224
|
+
}
|
|
225
|
+
/**
|
|
226
|
+
* When `serialize: 'records'` is configured, writes the full related
|
|
227
|
+
* record object instead of just the id.
|
|
228
|
+
*/
|
|
229
|
+
serializeBelongsTo(s, r, e) {
|
|
230
|
+
var o;
|
|
231
|
+
const n = (o = this.attrs) == null ? void 0 : o[e.name];
|
|
232
|
+
if ((n == null ? void 0 : n.serialize) === "records") {
|
|
233
|
+
const l = s.belongsTo(e.name);
|
|
234
|
+
r[this.keyForRelationship(e.name)] = l ?? null;
|
|
235
|
+
return;
|
|
236
|
+
}
|
|
237
|
+
super.serializeBelongsTo(s, r, e);
|
|
238
|
+
}
|
|
239
|
+
/**
|
|
240
|
+
* Normalizes a single embedded resource object using the related model's
|
|
241
|
+
* type as a placeholder `ModelClassMeta`.
|
|
242
|
+
*/
|
|
243
|
+
extractEmbeddedResource(s, r, e) {
|
|
244
|
+
if (!e || typeof e != "object" || Array.isArray(e))
|
|
245
|
+
return null;
|
|
246
|
+
const n = {
|
|
247
|
+
modelName: r.type,
|
|
248
|
+
attributes: /* @__PURE__ */ new Map(),
|
|
249
|
+
relationships: /* @__PURE__ */ new Map()
|
|
250
|
+
};
|
|
251
|
+
return this.normalize(s, n, e);
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
return a;
|
|
255
|
+
}
|
|
256
|
+
export {
|
|
257
|
+
I as E,
|
|
258
|
+
z as J,
|
|
259
|
+
A as R
|
|
260
|
+
};
|
|
261
|
+
//# sourceMappingURL=EmbeddedRecordsMixin-VoHluHCT.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"EmbeddedRecordsMixin-VoHluHCT.js","sources":["../src/serializer/JsonSerializer.ts","../src/serializer/RestSerializer.ts","../src/serializer/EmbeddedRecordsMixin.ts"],"sourcesContent":["/**\n * Flat-JSON serializer for simple REST APIs.\n *\n * `JsonSerializer` expects payloads to be plain JSON objects or arrays with\n * no root-key wrapping. It is the lowest-level concrete serializer and the\n * base that `RestSerializer` extends.\n *\n * Normalization:\n * - Array payload → `{ data: [NormalizedResource, …] }`\n * - Object payload → `{ data: NormalizedResource }`\n * - `null` / `undefined` → `{ data: null }`\n *\n * Serialization:\n * - Iterates `@attr` → writes via `serializeAttribute`\n * - Iterates `@belongsTo` / `@hasMany` → writes via `serializeBelongsTo` /\n * `serializeHasMany`\n *\n * `normalizeResponse` automatically dispatches to the correct per-operation\n * hook (`normalizeFindRecordResponse`, etc.) when a subclass overrides them.\n * If no override exists it falls through to `_buildDocument`.\n */\n\nimport { injectable } from 'tsyringe';\nimport {\n Serializer,\n type ModelClassMeta,\n type NormalizeRequestType,\n type NormalizedDocument,\n type NormalizedResource,\n type SerializerSnapshot,\n} from './Serializer.js';\n\n@injectable()\nexport class JsonSerializer extends Serializer {\n static dispatchMethodName(\n requestType: NormalizeRequestType,\n ): keyof Serializer | null {\n switch (requestType) {\n case 'findRecord':\n return 'normalizeFindRecordResponse';\n case 'findAll':\n return 'normalizeFindAllResponse';\n case 'query':\n return 'normalizeQueryResponse';\n case 'queryRecord':\n return 'normalizeQueryRecordResponse';\n case 'createRecord':\n return 'normalizeCreateRecordResponse';\n case 'updateRecord':\n return 'normalizeUpdateRecordResponse';\n case 'deleteRecord':\n return 'normalizeDeleteRecordResponse';\n default:\n return null;\n }\n }\n\n /**\n * Normalizes a single flat JSON object into a `NormalizedResource`.\n * Returns `null` for absent or non-object payloads.\n */\n override normalize(\n _store: unknown,\n modelClass: ModelClassMeta,\n payload: unknown,\n _prop?: string,\n ): NormalizedResource | null {\n if (payload === null || payload === undefined) {\n return null;\n }\n if (typeof payload !== 'object') {\n return null;\n }\n const hash = payload as Record<string, unknown>;\n const id = this.extractId(modelClass, hash);\n const attributes = this.extractAttributes(modelClass, hash);\n const relationships = this.extractRelationships(modelClass, hash);\n\n const resource: NormalizedResource = {\n type: modelClass.modelName,\n id,\n attributes,\n };\n if (relationships && Object.keys(relationships).length > 0) {\n resource.relationships = relationships;\n }\n return resource;\n }\n\n /**\n * Entry point for normalization.\n *\n * Checks whether a subclass has overridden the relevant per-operation hook\n * (e.g. `normalizeFindRecordResponse`). If so, calls it; otherwise falls\n * through to `_buildDocument`.\n */\n override normalizeResponse(\n store: unknown,\n modelClass: ModelClassMeta,\n payload: unknown,\n id: string | null,\n requestType: NormalizeRequestType,\n ): NormalizedDocument {\n const methodName = JsonSerializer.dispatchMethodName(requestType);\n if (methodName) {\n const override = (this as unknown as Record<string, unknown>)[methodName];\n const baseImpl = (Serializer.prototype as unknown as Record<string, unknown>)[\n methodName\n ];\n if (typeof override === 'function' && override !== baseImpl) {\n return (override as (...args: unknown[]) => NormalizedDocument).call(\n this,\n store,\n modelClass,\n payload,\n id,\n requestType,\n );\n }\n }\n return this._buildDocument(store, modelClass, payload, id, requestType);\n }\n\n /**\n * Builds a `NormalizedDocument` from a raw payload.\n * Arrays are normalized item by item; plain objects are normalized as a\n * single resource.\n */\n protected _buildDocument(\n store: unknown,\n modelClass: ModelClassMeta,\n payload: unknown,\n _id: string | null,\n _requestType: NormalizeRequestType,\n ): NormalizedDocument {\n if (payload === null || payload === undefined) {\n return { data: null };\n }\n if (Array.isArray(payload)) {\n const data = payload\n .map((p) => this.normalize(store, modelClass, p))\n .filter((r): r is NormalizedResource => r !== null);\n return { data };\n }\n const data = this.normalize(store, modelClass, payload);\n return { data };\n }\n\n /**\n * Serializes a snapshot to a flat JSON object.\n * Includes `id` when `options.includeId` is `true`.\n */\n override serialize(\n snapshot: SerializerSnapshot,\n options?: { includeId?: boolean },\n ): Record<string, unknown> {\n const json: Record<string, unknown> = {};\n if (options?.includeId && snapshot.id !== null) {\n json[this.primaryKey] = snapshot.id;\n }\n snapshot.eachAttribute((key, meta) => {\n this.serializeAttribute(snapshot, json, key, meta);\n });\n snapshot.eachRelationship((_key, rel) => {\n if (rel.kind === 'belongsTo') {\n this.serializeBelongsTo(snapshot, json, rel);\n } else {\n this.serializeHasMany(snapshot, json, rel);\n }\n });\n return json;\n }\n}\n","/**\n * REST serializer for root-key payloads with optional sideloading.\n *\n * `RestSerializer` expects the primary data to be wrapped under a root key\n * that matches either the singular or plural model name:\n *\n * ```json\n * { \"post\": { \"id\": \"1\", \"title\": \"Hello\" } }\n * { \"posts\": [{ \"id\": \"1\", … }, { \"id\": \"2\", … }] }\n * ```\n *\n * Any additional keys in the payload are treated as sideloaded (compound)\n * data. `meta` and `links` keys are reserved and forwarded to the document.\n *\n * Sideloaded types are inferred from the payload key via `modelNameFromPayloadKey`\n * (default: singularization).\n *\n * Extends `JsonSerializer` so it inherits flat `normalize` and `serialize`\n * behaviour and only overrides document-level parsing via `_buildDocument`.\n */\n\nimport { injectable } from 'tsyringe';\nimport pluralize from 'pluralize';\nimport {\n type ModelClassMeta,\n type NormalizeRequestType,\n type NormalizedDocument,\n type NormalizedResource,\n} from './Serializer.js';\nimport { JsonSerializer } from './JsonSerializer.js';\n\n@injectable()\nexport class RestSerializer extends JsonSerializer {\n /**\n * Returns the plural payload key for a model name.\n * e.g. `'post'` → `'posts'`\n */\n payloadKeyFromModelName(modelName: string): string {\n return pluralize.plural(modelName);\n }\n\n /**\n * Returns the model name for a payload root key.\n * e.g. `'posts'` → `'post'`\n */\n modelNameFromPayloadKey(key: string): string {\n return pluralize.singular(key);\n }\n\n /**\n * Builds a `NormalizedDocument` from a root-key REST payload.\n *\n * - Looks for the model data under the singular or plural root key.\n * - Treats every other non-reserved key as a sideloaded type.\n * - Preserves `meta` and `links` from the root.\n */\n protected override _buildDocument(\n store: unknown,\n modelClass: ModelClassMeta,\n payload: unknown,\n _id: string | null,\n _requestType: NormalizeRequestType,\n ): NormalizedDocument {\n if (payload === null || payload === undefined || typeof payload !== 'object') {\n return { data: null };\n }\n const hash = payload as Record<string, unknown>;\n const singular = modelClass.modelName;\n const plural = this.payloadKeyFromModelName(singular);\n\n let data: NormalizedResource | NormalizedResource[] | null = null;\n const primaryKeys = new Set<string>();\n\n if (singular in hash) {\n primaryKeys.add(singular);\n const raw = hash[singular];\n if (Array.isArray(raw)) {\n data = raw\n .map((entry) => this.normalize(store, modelClass, entry))\n .filter((resource): resource is NormalizedResource => resource !== null);\n } else {\n data = this.normalize(store, modelClass, raw);\n }\n } else if (plural in hash) {\n primaryKeys.add(plural);\n const raw = hash[plural];\n if (Array.isArray(raw)) {\n data = raw\n .map((entry) => this.normalize(store, modelClass, entry))\n .filter((resource): resource is NormalizedResource => resource !== null);\n } else {\n data = this.normalize(store, modelClass, raw);\n }\n }\n\n // Collect sideloaded records from all remaining root keys.\n const included: NormalizedResource[] = [];\n for (const [key, value] of Object.entries(hash)) {\n if (primaryKeys.has(key)) {\n continue;\n }\n if (key === 'meta' || key === 'links') {\n continue;\n }\n const sideloadType = this.modelNameFromPayloadKey(key);\n const sideloadClass: ModelClassMeta = {\n modelName: sideloadType,\n attributes: new Map(),\n relationships: new Map(),\n };\n if (Array.isArray(value)) {\n for (const item of value) {\n const normalized = this.normalize(store, sideloadClass, item);\n if (normalized) {\n included.push(normalized);\n }\n }\n } else if (value && typeof value === 'object') {\n const normalized = this.normalize(store, sideloadClass, value);\n if (normalized) {\n included.push(normalized);\n }\n }\n }\n\n const doc: NormalizedDocument = { data };\n if (included.length > 0) {\n doc.included = included;\n }\n if (hash.meta && typeof hash.meta === 'object') {\n doc.meta = hash.meta as Record<string, unknown>;\n }\n if (hash.links && typeof hash.links === 'object') {\n doc.links = hash.links as Record<string, string>;\n }\n return doc;\n }\n}\n","/**\n * Mixin that adds support for embedded (nested) records in REST payloads.\n *\n * Apply with:\n * ```ts\n * class PostSerializer extends EmbeddedRecordsMixin(RestSerializer) {\n * attrs = {\n * comments: { embedded: 'always' },\n * author: { embedded: 'always', serialize: 'records' },\n * };\n * }\n * ```\n *\n * ## How it works\n *\n * ### Deserialization\n * When `embedded: 'always'` is set for a relationship, `normalize()` intercepts\n * the raw payload before passing it to `super.normalize()`:\n * - For `hasMany`: replaces the nested array with a plain id array and queues\n * each nested object as an `included` resource.\n * - For `belongsTo`: replaces the nested object with the extracted id and\n * queues the nested object as an `included` resource.\n *\n * Queued resources are collected during `normalizeResponse()` and appended to\n * `document.included` so the `Store` can push them into the identity map.\n *\n * ### Serialization\n * When `serialize: 'records'` is set, `serializeHasMany` / `serializeBelongsTo`\n * write the full related record(s) into the payload instead of just ids.\n *\n * ## Configuration\n *\n * Each entry in `attrs` is an `EmbeddedAttrConfig`:\n * - `embedded: 'always'` — enable embedded deserialization.\n * - `serialize: 'records'` — write full records on serialize.\n * - `serialize: 'ids'` — write id array on serialize (default).\n * - `serialize: false` — omit relationship from serialized payload.\n * - `deserialize: 'records'` — same as `embedded: 'always'`.\n * - `deserialize: false` — ignore this relationship during normalization.\n */\n\nimport type { RelationshipDef } from '@mobx-data/schema';\nimport type {\n ModelClassMeta,\n NormalizeRequestType,\n NormalizedDocument,\n NormalizedResource,\n SerializerSnapshot,\n} from './Serializer.js';\n\n/** Per-relationship embedding configuration. */\nexport interface EmbeddedAttrConfig {\n /** `'always'` to deserialize embedded records; `'never'` to skip. */\n embedded?: 'always' | 'never';\n /** `'records'` to serialize full objects; `'ids'` for ids only; `false` to omit. */\n serialize?: 'records' | 'ids' | false;\n /** `'records'` to deserialize embedded objects; `'ids'` for plain ids; `false` to skip. */\n deserialize?: 'records' | 'ids' | false;\n}\n\n/** Map of relationship name → embedding config. */\nexport interface EmbeddedRecordsAttrs {\n [key: string]: EmbeddedAttrConfig;\n}\n\n/**\n * The minimal serializer interface required by the mixin.\n * Any class extending `JsonSerializer` satisfies this.\n */\nexport interface JsonSerializerLike {\n attrs?: EmbeddedRecordsAttrs;\n primaryKey: string;\n normalize(\n store: unknown,\n modelClass: ModelClassMeta,\n payload: unknown,\n prop?: string,\n ): NormalizedResource | null;\n normalizeResponse(\n store: unknown,\n modelClass: ModelClassMeta,\n payload: unknown,\n id: string | null,\n requestType: NormalizeRequestType,\n ): NormalizedDocument;\n serialize(\n snapshot: SerializerSnapshot,\n options?: { includeId?: boolean },\n ): Record<string, unknown>;\n serializeHasMany(\n snapshot: SerializerSnapshot,\n json: Record<string, unknown>,\n relationship: RelationshipDef,\n ): void;\n serializeBelongsTo(\n snapshot: SerializerSnapshot,\n json: Record<string, unknown>,\n relationship: RelationshipDef,\n ): void;\n keyForAttribute(key: string): string;\n keyForRelationship(key: string): string;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype Constructor<T> = new (...args: any[]) => T;\n\n/**\n * Returns a new class that extends `Base` with embedded-record support.\n * `Base` must be (or extend) `JsonSerializer`.\n */\nexport function EmbeddedRecordsMixin<\n TBase extends Constructor<JsonSerializerLike>,\n>(Base: TBase): TBase {\n class WithEmbeddedRecords extends Base {\n override attrs?: EmbeddedRecordsAttrs;\n\n /** Accumulates extracted embedded resources during a `normalizeResponse` call. */\n private pendingIncluded: NormalizedResource[] = [];\n\n /**\n * Intercepts raw payload hashes to extract embedded records.\n *\n * For each relationship configured with `embedded: 'always'`:\n * - Recursively normalizes the embedded object(s) and adds them to\n * `pendingIncluded`.\n * - Replaces the embedded value in the hash with the extracted id(s) so\n * `super.normalize` treats it as a plain id reference.\n */\n override normalize(\n store: unknown,\n modelClass: ModelClassMeta,\n payload: unknown,\n prop?: string,\n ): NormalizedResource | null {\n if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {\n return super.normalize(store, modelClass, payload, prop);\n }\n const src = payload as Record<string, unknown>;\n const attrs = this.attrs ?? {};\n const hash: Record<string, unknown> = { ...src };\n\n for (const [name, rel] of modelClass.relationships) {\n const cfg = attrs[name];\n if (!cfg || cfg.embedded !== 'always') {\n continue;\n }\n const raw = hash[name];\n if (raw === undefined || raw === null) {\n continue;\n }\n\n if (rel.kind === 'hasMany' && Array.isArray(raw)) {\n const ids: string[] = [];\n for (const item of raw) {\n const extracted = this.extractEmbeddedResource(store, rel, item);\n if (extracted && extracted.id !== null) {\n ids.push(extracted.id);\n this.pendingIncluded.push(extracted);\n }\n }\n hash[name] = ids;\n } else if (\n rel.kind === 'belongsTo'\n && typeof raw === 'object'\n && !Array.isArray(raw)\n ) {\n const extracted = this.extractEmbeddedResource(store, rel, raw);\n if (extracted && extracted.id !== null) {\n this.pendingIncluded.push(extracted);\n hash[name] = extracted.id;\n }\n }\n }\n\n return super.normalize(store, modelClass, hash, prop);\n }\n\n /**\n * Resets `pendingIncluded`, delegates to `super.normalizeResponse`, then\n * appends any extracted embedded resources to `document.included`.\n */\n override normalizeResponse(\n store: unknown,\n modelClass: ModelClassMeta,\n payload: unknown,\n id: string | null,\n requestType: NormalizeRequestType,\n ): NormalizedDocument {\n this.pendingIncluded = [];\n const doc = super.normalizeResponse(store, modelClass, payload, id, requestType);\n if (this.pendingIncluded.length > 0) {\n const included = doc.included ? [...doc.included] : [];\n included.push(...this.pendingIncluded);\n doc.included = included;\n this.pendingIncluded = [];\n }\n return doc;\n }\n\n /**\n * When `serialize: 'records'` is configured, writes the full related\n * record objects instead of just ids.\n */\n override serializeHasMany(\n snapshot: SerializerSnapshot,\n json: Record<string, unknown>,\n relationship: RelationshipDef,\n ): void {\n const cfg = this.attrs?.[relationship.name];\n if (cfg?.serialize === 'records') {\n const records = snapshot.hasMany(relationship.name) as unknown[];\n json[this.keyForRelationship(relationship.name)] = records ?? [];\n return;\n }\n super.serializeHasMany(snapshot, json, relationship);\n }\n\n /**\n * When `serialize: 'records'` is configured, writes the full related\n * record object instead of just the id.\n */\n override serializeBelongsTo(\n snapshot: SerializerSnapshot,\n json: Record<string, unknown>,\n relationship: RelationshipDef,\n ): void {\n const cfg = this.attrs?.[relationship.name];\n if (cfg?.serialize === 'records') {\n const record = snapshot.belongsTo(relationship.name);\n json[this.keyForRelationship(relationship.name)] = record ?? null;\n return;\n }\n super.serializeBelongsTo(snapshot, json, relationship);\n }\n\n /**\n * Normalizes a single embedded resource object using the related model's\n * type as a placeholder `ModelClassMeta`.\n */\n private extractEmbeddedResource(\n store: unknown,\n rel: RelationshipDef,\n item: unknown,\n ): NormalizedResource | null {\n if (!item || typeof item !== 'object' || Array.isArray(item)) {\n return null;\n }\n const embeddedClass: ModelClassMeta = {\n modelName: rel.type,\n attributes: new Map(),\n relationships: new Map(),\n };\n return this.normalize(store, embeddedClass, item);\n }\n }\n return WithEmbeddedRecords as unknown as TBase;\n}\n"],"names":["JsonSerializer","Serializer","requestType","_store","modelClass","payload","_prop","hash","id","attributes","relationships","resource","store","methodName","override","baseImpl","_id","_requestType","p","r","data","snapshot","options","json","key","meta","_key","rel","__decorateClass","injectable","RestSerializer","modelName","pluralize","singular","plural","primaryKeys","raw","entry","included","value","sideloadClass","item","normalized","doc","EmbeddedRecordsMixin","Base","WithEmbeddedRecords","prop","src","attrs","name","cfg","ids","extracted","relationship","_a","records","record","embeddedClass"],"mappings":";;;;;;;;AAiCO,IAAMA,IAAN,cAA6BC,EAAW;AAAA,EAC7C,OAAO,mBACLC,GACyB;AACzB,YAAQA,GAAA;AAAA,MACN,KAAK;AACH,eAAO;AAAA,MACT,KAAK;AACH,eAAO;AAAA,MACT,KAAK;AACH,eAAO;AAAA,MACT,KAAK;AACH,eAAO;AAAA,MACT,KAAK;AACH,eAAO;AAAA,MACT,KAAK;AACH,eAAO;AAAA,MACT,KAAK;AACH,eAAO;AAAA,MACT;AACE,eAAO;AAAA,IAAA;AAAA,EAEb;AAAA;AAAA;AAAA;AAAA;AAAA,EAMS,UACPC,GACAC,GACAC,GACAC,GAC2B;AAI3B,QAHID,KAAY,QAGZ,OAAOA,KAAY;AACrB,aAAO;AAET,UAAME,IAAOF,GACPG,IAAK,KAAK,UAAUJ,GAAYG,CAAI,GACpCE,IAAa,KAAK,kBAAkBL,GAAYG,CAAI,GACpDG,IAAgB,KAAK,qBAAqBN,GAAYG,CAAI,GAE1DI,IAA+B;AAAA,MACnC,MAAMP,EAAW;AAAA,MACjB,IAAAI;AAAA,MACA,YAAAC;AAAA,IAAA;AAEF,WAAIC,KAAiB,OAAO,KAAKA,CAAa,EAAE,SAAS,MACvDC,EAAS,gBAAgBD,IAEpBC;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASS,kBACPC,GACAR,GACAC,GACAG,GACAN,GACoB;AACpB,UAAMW,IAAab,EAAe,mBAAmBE,CAAW;AAChE,QAAIW,GAAY;AACd,YAAMC,IAAY,KAA4CD,CAAU,GAClEE,IAAYd,EAAW,UAC3BY,CACF;AACA,UAAI,OAAOC,KAAa,cAAcA,MAAaC;AACjD,eAAQD,EAAwD;AAAA,UAC9D;AAAA,UACAF;AAAA,UACAR;AAAA,UACAC;AAAA,U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AAIH,KAAA,gBAAAA,EAAK,eAAc,WAAW;AAChC,cAAMK,IAAUnC,EAAS,QAAQiC,EAAa,IAAI;AAClD,QAAA/B,EAAK,KAAK,mBAAmB+B,EAAa,IAAI,CAAC,IAAIE,KAAW,CAAA;AAC9D;AAAA,MACF;AACA,YAAM,iBAAiBnC,GAAUE,GAAM+B,CAAY;AAAA,IACrD;AAAA;AAAA;AAAA;AAAA;AAAA,IAMS,mBACPjC,GACAE,GACA+B,GACM;;AACN,YAAMH,KAAMI,IAAA,KAAK,UAAL,gBAAAA,EAAaD,EAAa;AACtC,WAAIH,KAAA,gBAAAA,EAAK,eAAc,WAAW;AAChC,cAAMM,IAASpC,EAAS,UAAUiC,EAAa,IAAI;AACnD,QAAA/B,EAAK,KAAK,mBAAmB+B,EAAa,IAAI,CAAC,IAAIG,KAAU;AAC7D;AAAA,MACF;AACA,YAAM,mBAAmBpC,GAAUE,GAAM+B,CAAY;AAAA,IACvD;AAAA;AAAA;AAAA;AAAA;AAAA,IAMQ,wBACN1C,GACAe,GACAc,GAC2B;AAC3B,UAAI,CAACA,KAAQ,OAAOA,KAAS,YAAY,MAAM,QAAQA,CAAI;AACzD,eAAO;AAET,YAAMiB,IAAgC;AAAA,QACpC,WAAW/B,EAAI;AAAA,QACf,gCAAgB,IAAA;AAAA,QAChB,mCAAmB,IAAA;AAAA,MAAI;AAEzB,aAAO,KAAK,UAAUf,GAAO8C,GAAejB,CAAI;AAAA,IAClD;AAAA,EAAA;AAEF,SAAOK;AACT;"}
|
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
import { injectable as f } from "tsyringe";
|
|
2
|
+
import { R as h } from "./RestAdapter-B4aRvs4m.js";
|
|
3
|
+
import m from "pluralize";
|
|
4
|
+
import { S as b } from "./Serializer-FxJbsZ50.js";
|
|
5
|
+
var _ = Object.getOwnPropertyDescriptor, g = (t, i, a, s) => {
|
|
6
|
+
for (var r = s > 1 ? void 0 : s ? _(i, a) : i, e = t.length - 1, n; e >= 0; e--)
|
|
7
|
+
(n = t[e]) && (r = n(r) || r);
|
|
8
|
+
return r;
|
|
9
|
+
};
|
|
10
|
+
let p = class extends h {
|
|
11
|
+
constructor() {
|
|
12
|
+
super(...arguments), this.coalesceFindRequests = !0;
|
|
13
|
+
}
|
|
14
|
+
/** Returns JSON:API `Accept` header alongside any custom headers. */
|
|
15
|
+
defaultHeaders() {
|
|
16
|
+
return {
|
|
17
|
+
Accept: "application/vnd.api+json",
|
|
18
|
+
...this.headers
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
/** Returns JSON:API `Content-Type` header for mutation requests. */
|
|
22
|
+
mutationHeaders() {
|
|
23
|
+
return {
|
|
24
|
+
"Content-Type": "application/vnd.api+json",
|
|
25
|
+
...this.defaultHeaders()
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Sends a PATCH request to update a record (JSON:API mandates PATCH, not PUT).
|
|
30
|
+
*/
|
|
31
|
+
async updateRecord(t, i, a) {
|
|
32
|
+
const s = this.buildURL(i, a.id, a, "updateRecord");
|
|
33
|
+
return this._fetchJSON(s, {
|
|
34
|
+
method: "PATCH",
|
|
35
|
+
headers: this.mutationHeaders(),
|
|
36
|
+
body: JSON.stringify(this._serializeForUpdate(a))
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Sends a PATCH request with only the changed attributes (partial update).
|
|
41
|
+
* Produces a JSON:API document with only the dirty attribute keys.
|
|
42
|
+
*/
|
|
43
|
+
async patchRecord(t, i, a) {
|
|
44
|
+
const s = this.buildURL(i, a.id, a, "updateRecord"), r = a.changedAttributes(), e = {};
|
|
45
|
+
for (const [l, [, d]] of Object.entries(r))
|
|
46
|
+
e[l] = d;
|
|
47
|
+
const n = {
|
|
48
|
+
data: {
|
|
49
|
+
type: i,
|
|
50
|
+
id: a.id,
|
|
51
|
+
attributes: e
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
return this._fetchJSON(s, {
|
|
55
|
+
method: "PATCH",
|
|
56
|
+
headers: this.mutationHeaders(),
|
|
57
|
+
body: JSON.stringify(n)
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Extracts the raw data object from the snapshot for use as the PATCH body.
|
|
62
|
+
* Subclasses may override this to produce a full JSON:API `{ data: … }` document.
|
|
63
|
+
*/
|
|
64
|
+
_serializeForUpdate(t) {
|
|
65
|
+
const i = t.record;
|
|
66
|
+
return i._data ? { ...i._data } : {};
|
|
67
|
+
}
|
|
68
|
+
};
|
|
69
|
+
p = g([
|
|
70
|
+
f()
|
|
71
|
+
], p);
|
|
72
|
+
var A = Object.getOwnPropertyDescriptor, v = (t, i, a, s) => {
|
|
73
|
+
for (var r = s > 1 ? void 0 : s ? A(i, a) : i, e = t.length - 1, n; e >= 0; e--)
|
|
74
|
+
(n = t[e]) && (r = n(r) || r);
|
|
75
|
+
return r;
|
|
76
|
+
};
|
|
77
|
+
let y = class extends b {
|
|
78
|
+
/**
|
|
79
|
+
* Returns the plural JSON:API `type` string for a model name.
|
|
80
|
+
* e.g. `'post'` → `'posts'`
|
|
81
|
+
*/
|
|
82
|
+
payloadKeyFromModelName(t) {
|
|
83
|
+
return m.plural(t);
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Returns the model name for a JSON:API `type` string.
|
|
87
|
+
* e.g. `'posts'` → `'post'`
|
|
88
|
+
*/
|
|
89
|
+
modelNameFromPayloadKey(t) {
|
|
90
|
+
return m.singular(t);
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Normalizes a single JSON:API resource object into a `NormalizedResource`.
|
|
94
|
+
* Returns `null` for absent, non-object, or type-less payloads.
|
|
95
|
+
*/
|
|
96
|
+
normalize(t, i, a, s) {
|
|
97
|
+
if (!a || typeof a != "object" || Array.isArray(a))
|
|
98
|
+
return null;
|
|
99
|
+
const r = a;
|
|
100
|
+
if (!r.type)
|
|
101
|
+
return null;
|
|
102
|
+
const e = {
|
|
103
|
+
type: this.modelNameFromPayloadKey(r.type),
|
|
104
|
+
id: r.id === null || r.id === void 0 ? null : String(r.id)
|
|
105
|
+
};
|
|
106
|
+
if (r.attributes && (e.attributes = { ...r.attributes }), r.relationships) {
|
|
107
|
+
const n = {};
|
|
108
|
+
for (const [l, d] of Object.entries(r.relationships))
|
|
109
|
+
d.data === null ? n[l] = { data: null } : Array.isArray(d.data) ? n[l] = {
|
|
110
|
+
data: d.data.map((o) => ({
|
|
111
|
+
type: this.modelNameFromPayloadKey(o.type),
|
|
112
|
+
id: String(o.id)
|
|
113
|
+
}))
|
|
114
|
+
} : n[l] = {
|
|
115
|
+
data: {
|
|
116
|
+
type: this.modelNameFromPayloadKey(d.data.type),
|
|
117
|
+
id: String(d.data.id)
|
|
118
|
+
}
|
|
119
|
+
};
|
|
120
|
+
e.relationships = n;
|
|
121
|
+
}
|
|
122
|
+
return e;
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* Normalizes a full JSON:API compound document.
|
|
126
|
+
*
|
|
127
|
+
* - `data` (single or array) → primary resources
|
|
128
|
+
* - `included` → side-loaded resources pushed to `normalizedDoc.included`
|
|
129
|
+
* - `meta` and `links` → forwarded as-is
|
|
130
|
+
*/
|
|
131
|
+
normalizeResponse(t, i, a, s, r) {
|
|
132
|
+
if (!a || typeof a != "object")
|
|
133
|
+
return { data: null };
|
|
134
|
+
const e = a;
|
|
135
|
+
let n = null;
|
|
136
|
+
e.data === null || e.data === void 0 ? n = null : Array.isArray(e.data) ? n = e.data.map((d) => this.normalize(t, i, d)).filter((d) => d !== null) : n = this.normalize(t, i, e.data);
|
|
137
|
+
const l = { data: n };
|
|
138
|
+
if (e.included && e.included.length > 0) {
|
|
139
|
+
const d = [];
|
|
140
|
+
for (const o of e.included) {
|
|
141
|
+
const c = {
|
|
142
|
+
modelName: this.modelNameFromPayloadKey(o.type),
|
|
143
|
+
attributes: /* @__PURE__ */ new Map(),
|
|
144
|
+
relationships: /* @__PURE__ */ new Map()
|
|
145
|
+
}, u = this.normalize(t, c, o);
|
|
146
|
+
u && d.push(u);
|
|
147
|
+
}
|
|
148
|
+
l.included = d;
|
|
149
|
+
}
|
|
150
|
+
return e.meta && (l.meta = e.meta), e.links && (l.links = e.links), l;
|
|
151
|
+
}
|
|
152
|
+
/**
|
|
153
|
+
* Serializes a record snapshot to a JSON:API `{ data: … }` document.
|
|
154
|
+
*
|
|
155
|
+
* Attributes are placed in `data.attributes`; relationships are placed in
|
|
156
|
+
* `data.relationships` with proper `{ data: { type, id } }` structure.
|
|
157
|
+
* `id` is included in `data` when `options.includeId` is `true`.
|
|
158
|
+
*/
|
|
159
|
+
serialize(t, i) {
|
|
160
|
+
const a = {};
|
|
161
|
+
t.eachAttribute((e) => {
|
|
162
|
+
a[this.keyForAttribute(e)] = t.attr(e);
|
|
163
|
+
});
|
|
164
|
+
const s = {};
|
|
165
|
+
t.eachRelationship((e, n) => {
|
|
166
|
+
const { name: l } = n, d = this.keyForRelationship(l), o = this.payloadKeyFromModelName(n.type);
|
|
167
|
+
if (n.kind === "belongsTo") {
|
|
168
|
+
const c = t.belongsTo(l);
|
|
169
|
+
s[d] = c && c.id != null ? { data: { type: o, id: String(c.id) } } : { data: null };
|
|
170
|
+
} else {
|
|
171
|
+
const c = t.hasMany(l) ?? [];
|
|
172
|
+
s[d] = {
|
|
173
|
+
data: c.map((u) => ({
|
|
174
|
+
type: o,
|
|
175
|
+
id: String(u.id)
|
|
176
|
+
}))
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
});
|
|
180
|
+
const r = {
|
|
181
|
+
type: this.payloadKeyFromModelName(t.modelName),
|
|
182
|
+
attributes: a
|
|
183
|
+
};
|
|
184
|
+
return i != null && i.includeId && t.id !== null && (r.id = t.id), Object.keys(s).length > 0 && (r.relationships = s), { data: r };
|
|
185
|
+
}
|
|
186
|
+
};
|
|
187
|
+
y = v([
|
|
188
|
+
f()
|
|
189
|
+
], y);
|
|
190
|
+
export {
|
|
191
|
+
p as J,
|
|
192
|
+
y as a
|
|
193
|
+
};
|
|
194
|
+
//# sourceMappingURL=JsonApiSerializer-CC5HXp4b.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"JsonApiSerializer-CC5HXp4b.js","sources":["../src/json-api/JsonApiAdapter.ts","../src/json-api/JsonApiSerializer.ts"],"sourcesContent":["/**\n * Adapter that implements the [JSON:API](https://jsonapi.org) specification.\n *\n * Extends `RestAdapter` with the following differences:\n *\n * - **MIME types** — `Accept` and `Content-Type` headers are set to\n * `application/vnd.api+json` as required by the spec.\n * - **PATCH for updates** — `updateRecord` uses `PATCH` instead of `PUT`.\n * - **`coalesceFindRequests: true`** — the store coalesces separate\n * `findRecord` calls into a single `findMany` request.\n *\n * URL construction is inherited from `RestAdapter` / `Adapter` unchanged;\n * override `pathForType` or `urlFor*` methods to customize.\n */\n\nimport { injectable } from 'tsyringe';\nimport { RestAdapter, type AdapterSnapshot } from '@mobx-data/adapter';\n\n@injectable()\nexport class JsonApiAdapter extends RestAdapter {\n /** Always coalesce `findRecord` calls into a single `findMany` request. */\n override coalesceFindRequests = true;\n\n /** Returns JSON:API `Accept` header alongside any custom headers. */\n override defaultHeaders(): Record<string, string> {\n return {\n Accept: 'application/vnd.api+json',\n ...this.headers,\n };\n }\n\n /** Returns JSON:API `Content-Type` header for mutation requests. */\n override mutationHeaders(): Record<string, string> {\n return {\n 'Content-Type': 'application/vnd.api+json',\n ...this.defaultHeaders(),\n };\n }\n\n /**\n * Sends a PATCH request to update a record (JSON:API mandates PATCH, not PUT).\n */\n override async updateRecord(\n _store: unknown,\n modelName: string,\n snapshot: AdapterSnapshot,\n ): Promise<unknown> {\n const url = this.buildURL(modelName, snapshot.id, snapshot, 'updateRecord');\n return this._fetchJSON(url, {\n method: 'PATCH',\n headers: this.mutationHeaders(),\n body: JSON.stringify(this._serializeForUpdate(snapshot)),\n });\n }\n\n /**\n * Sends a PATCH request with only the changed attributes (partial update).\n * Produces a JSON:API document with only the dirty attribute keys.\n */\n override async patchRecord(\n _store: unknown,\n modelName: string,\n snapshot: AdapterSnapshot,\n ): Promise<unknown> {\n const url = this.buildURL(modelName, snapshot.id, snapshot, 'updateRecord');\n const changed = snapshot.changedAttributes();\n const attributes: Record<string, unknown> = {};\n for (const [key, [, current]] of Object.entries(changed)) {\n attributes[key] = current;\n }\n const body = {\n data: {\n type: modelName,\n id: snapshot.id,\n attributes,\n },\n };\n return this._fetchJSON(url, {\n method: 'PATCH',\n headers: this.mutationHeaders(),\n body: JSON.stringify(body),\n });\n }\n\n /**\n * Extracts the raw data object from the snapshot for use as the PATCH body.\n * Subclasses may override this to produce a full JSON:API `{ data: … }` document.\n */\n protected _serializeForUpdate(snapshot: AdapterSnapshot): Record<string, unknown> {\n const rec = snapshot.record as { _data?: Record<string, unknown> };\n return rec._data ? { ...rec._data } : {};\n }\n}\n","/**\n * Serializer that implements the [JSON:API](https://jsonapi.org) specification.\n *\n * ## Normalization\n *\n * Parses a JSON:API compound document `{ data, included, meta, links }` into\n * a `NormalizedDocument`.\n *\n * For each resource object:\n * - `type` is converted from JSON:API plural form to model name via\n * `modelNameFromPayloadKey` (singularization).\n * - `id` is coerced to a string.\n * - `attributes` are copied directly.\n * - `relationships` data refs (`{ type, id }`) are normalized the same way.\n *\n * Side-loaded records in `included` are normalized individually, each using\n * its own `type` as the model class placeholder.\n *\n * ## Serialization\n *\n * Produces a JSON:API resource object wrapped in `{ data: … }`:\n *\n * ```json\n * {\n * \"data\": {\n * \"type\": \"posts\",\n * \"attributes\": { \"title\": \"Hello\" },\n * \"relationships\": {\n * \"author\": { \"data\": { \"type\": \"users\", \"id\": \"1\" } }\n * }\n * }\n * }\n * ```\n *\n * `id` is included when `options.includeId` is `true`.\n */\n\nimport { injectable } from 'tsyringe';\nimport pluralize from 'pluralize';\nimport {\n Serializer,\n type ModelClassMeta,\n type NormalizeRequestType,\n type NormalizedDocument,\n type NormalizedResource,\n type SerializerSnapshot,\n} from '@mobx-data/serializer';\n\n/** Internal shape of a raw JSON:API resource object. */\ninterface JsonApiResource {\n type: string;\n id?: string | number | null;\n attributes?: Record<string, unknown>;\n relationships?: Record<string, {\n data:\n | { type: string; id: string | number }\n | Array<{ type: string; id: string | number }>\n | null;\n }>;\n}\n\n@injectable()\nexport class JsonApiSerializer extends Serializer {\n /**\n * Returns the plural JSON:API `type` string for a model name.\n * e.g. `'post'` → `'posts'`\n */\n payloadKeyFromModelName(modelName: string): string {\n return pluralize.plural(modelName);\n }\n\n /**\n * Returns the model name for a JSON:API `type` string.\n * e.g. `'posts'` → `'post'`\n */\n modelNameFromPayloadKey(key: string): string {\n return pluralize.singular(key);\n }\n\n /**\n * Normalizes a single JSON:API resource object into a `NormalizedResource`.\n * Returns `null` for absent, non-object, or type-less payloads.\n */\n override normalize(\n _store: unknown,\n _modelClass: ModelClassMeta,\n payload: unknown,\n _prop?: string,\n ): NormalizedResource | null {\n if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {\n return null;\n }\n const resource = payload as JsonApiResource;\n if (!resource.type) {\n return null;\n }\n const normalized: NormalizedResource = {\n type: this.modelNameFromPayloadKey(resource.type),\n id: resource.id === null || resource.id === undefined ? null : String(resource.id),\n };\n if (resource.attributes) {\n normalized.attributes = { ...resource.attributes };\n }\n if (resource.relationships) {\n const relationships: NonNullable<NormalizedResource['relationships']> = {};\n for (const [name, rel] of Object.entries(resource.relationships)) {\n if (rel.data === null) {\n relationships[name] = { data: null };\n } else if (Array.isArray(rel.data)) {\n relationships[name] = {\n data: rel.data.map((ref) => ({\n type: this.modelNameFromPayloadKey(ref.type),\n id: String(ref.id),\n })),\n };\n } else {\n relationships[name] = {\n data: {\n type: this.modelNameFromPayloadKey(rel.data.type),\n id: String(rel.data.id),\n },\n };\n }\n }\n normalized.relationships = relationships;\n }\n return normalized;\n }\n\n /**\n * Normalizes a full JSON:API compound document.\n *\n * - `data` (single or array) → primary resources\n * - `included` → side-loaded resources pushed to `normalizedDoc.included`\n * - `meta` and `links` → forwarded as-is\n */\n override normalizeResponse(\n store: unknown,\n modelClass: ModelClassMeta,\n payload: unknown,\n _id: string | null,\n _requestType: NormalizeRequestType,\n ): NormalizedDocument {\n if (!payload || typeof payload !== 'object') {\n return { data: null };\n }\n const doc = payload as {\n data?: JsonApiResource | JsonApiResource[] | null;\n included?: JsonApiResource[];\n meta?: Record<string, unknown>;\n links?: Record<string, string>;\n };\n\n let data: NormalizedResource | NormalizedResource[] | null = null;\n if (doc.data === null || doc.data === undefined) {\n data = null;\n } else if (Array.isArray(doc.data)) {\n data = doc.data\n .map((resource) => this.normalize(store, modelClass, resource))\n .filter((resource): resource is NormalizedResource => resource !== null);\n } else {\n data = this.normalize(store, modelClass, doc.data);\n }\n\n const normalizedDoc: NormalizedDocument = { data };\n if (doc.included && doc.included.length > 0) {\n const included: NormalizedResource[] = [];\n for (const resource of doc.included) {\n const placeholder: ModelClassMeta = {\n modelName: this.modelNameFromPayloadKey(resource.type),\n attributes: new Map(),\n relationships: new Map(),\n };\n const normalized = this.normalize(store, placeholder, resource);\n if (normalized) {\n included.push(normalized);\n }\n }\n normalizedDoc.included = included;\n }\n if (doc.meta) {\n normalizedDoc.meta = doc.meta;\n }\n if (doc.links) {\n normalizedDoc.links = doc.links;\n }\n return normalizedDoc;\n }\n\n /**\n * Serializes a record snapshot to a JSON:API `{ data: … }` document.\n *\n * Attributes are placed in `data.attributes`; relationships are placed in\n * `data.relationships` with proper `{ data: { type, id } }` structure.\n * `id` is included in `data` when `options.includeId` is `true`.\n */\n override serialize(\n snapshot: SerializerSnapshot,\n options?: { includeId?: boolean },\n ): Record<string, unknown> {\n const attributes: Record<string, unknown> = {};\n snapshot.eachAttribute((key) => {\n attributes[this.keyForAttribute(key)] = snapshot.attr(key);\n });\n\n const relationships: Record<string, { data: unknown }> = {};\n snapshot.eachRelationship((_key, rel) => {\n const { name } = rel;\n const payloadKey = this.keyForRelationship(name);\n const payloadType = this.payloadKeyFromModelName(rel.type);\n if (rel.kind === 'belongsTo') {\n const target = snapshot.belongsTo(name) as\n | { id: string; type?: string }\n | null\n | undefined;\n relationships[payloadKey] = target && target.id != null\n ? { data: { type: payloadType, id: String(target.id) } }\n : { data: null };\n } else {\n const targets = (snapshot.hasMany(name) as Array<{\n id: string; type?: string;\n }> | null) ?? [];\n relationships[payloadKey] = {\n data: targets.map((target) => ({\n type: payloadType,\n id: String(target.id),\n })),\n };\n }\n });\n\n const data: Record<string, unknown> = {\n type: this.payloadKeyFromModelName(snapshot.modelName),\n attributes,\n };\n if (options?.includeId && snapshot.id !== null) {\n data.id = snapshot.id;\n }\n if (Object.keys(relationships).length > 0) {\n data.relationships = relationships;\n }\n\n return { data };\n }\n}\n"],"names":["JsonApiAdapter","RestAdapter","_store","modelName","snapshot","url","changed","attributes","key","current","body","rec","__decorateClass","injectable","JsonApiSerializer","Serializer","pluralize","_modelClass","payload","_prop","resource","normalized","relationships","name","rel","ref","store","modelClass","_id","_requestType","doc","data","normalizedDoc","included","placeholder","options","_key","payloadKey","payloadType","target","targets"],"mappings":";;;;;;;;;AAmBO,IAAMA,IAAN,cAA6BC,EAAY;AAAA,EAAzC,cAAA;AAAA,UAAA,GAAA,SAAA,GAEL,KAAS,uBAAuB;AAAA,EAAA;AAAA;AAAA,EAGvB,iBAAyC;AAChD,WAAO;AAAA,MACL,QAAQ;AAAA,MACR,GAAG,KAAK;AAAA,IAAA;AAAA,EAEZ;AAAA;AAAA,EAGS,kBAA0C;AACjD,WAAO;AAAA,MACL,gBAAgB;AAAA,MAChB,GAAG,KAAK,eAAA;AAAA,IAAe;AAAA,EAE3B;AAAA;AAAA;AAAA;AAAA,EAKA,MAAe,aACbC,GACAC,GACAC,GACkB;AAClB,UAAMC,IAAM,KAAK,SAASF,GAAWC,EAAS,IAAIA,GAAU,cAAc;AAC1E,WAAO,KAAK,WAAWC,GAAK;AAAA,MAC1B,QAAQ;AAAA,MACR,SAAS,KAAK,gBAAA;AAAA,MACd,MAAM,KAAK,UAAU,KAAK,oBAAoBD,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AO,EAAE,EAAA,MACjD,EAAE,MAAM,KAAA;AAAA,MACd,OAAO;AACL,cAAMC,IAAWpC,EAAS,QAAQmB,CAAI,KAExB,CAAA;AACd,QAAAD,EAAce,CAAU,IAAI;AAAA,UAC1B,MAAMG,EAAQ,IAAI,CAACD,OAAY;AAAA,YAC7B,MAAMD;AAAA,YACN,IAAI,OAAOC,EAAO,EAAE;AAAA,UAAA,EACpB;AAAA,QAAA;AAAA,MAEN;AAAA,IACF,CAAC;AAED,UAAMR,IAAgC;AAAA,MACpC,MAAM,KAAK,wBAAwB3B,EAAS,SAAS;AAAA,MACrD,YAAAG;AAAA,IAAA;AAEF,WAAI4B,KAAA,QAAAA,EAAS,aAAa/B,EAAS,OAAO,SACxC2B,EAAK,KAAK3B,EAAS,KAEjB,OAAO,KAAKkB,CAAa,EAAE,SAAS,MACtCS,EAAK,gBAAgBT,IAGhB,EAAE,MAAAS,EAAA;AAAA,EACX;AACF;AAtLajB,IAANF,EAAA;AAAA,EADNC,EAAA;AAAW,GACCC,CAAA;"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";const m=require("tsyringe"),h=require("./RestAdapter-CJOwTsKK.cjs"),y=require("pluralize"),f=require("./Serializer-95gi5edy.cjs");var A=Object.getOwnPropertyDescriptor,b=(c,t,n,r)=>{for(var a=r>1?void 0:r?A(t,n):t,i=c.length-1,e;i>=0;i--)(e=c[i])&&(a=e(a)||a);return a};exports.JsonApiAdapter=class extends h.RestAdapter{constructor(){super(...arguments),this.coalesceFindRequests=!0}defaultHeaders(){return{Accept:"application/vnd.api+json",...this.headers}}mutationHeaders(){return{"Content-Type":"application/vnd.api+json",...this.defaultHeaders()}}async updateRecord(t,n,r){const a=this.buildURL(n,r.id,r,"updateRecord");return this._fetchJSON(a,{method:"PATCH",headers:this.mutationHeaders(),body:JSON.stringify(this._serializeForUpdate(r))})}async patchRecord(t,n,r){const a=this.buildURL(n,r.id,r,"updateRecord"),i=r.changedAttributes(),e={};for(const[l,[,s]]of Object.entries(i))e[l]=s;const d={data:{type:n,id:r.id,attributes:e}};return this._fetchJSON(a,{method:"PATCH",headers:this.mutationHeaders(),body:JSON.stringify(d)})}_serializeForUpdate(t){const n=t.record;return n._data?{...n._data}:{}}};exports.JsonApiAdapter=b([m.injectable()],exports.JsonApiAdapter);var g=Object.getOwnPropertyDescriptor,_=(c,t,n,r)=>{for(var a=r>1?void 0:r?g(t,n):t,i=c.length-1,e;i>=0;i--)(e=c[i])&&(a=e(a)||a);return a};exports.JsonApiSerializer=class extends f.Serializer{payloadKeyFromModelName(t){return y.plural(t)}modelNameFromPayloadKey(t){return y.singular(t)}normalize(t,n,r,a){if(!r||typeof r!="object"||Array.isArray(r))return null;const i=r;if(!i.type)return null;const e={type:this.modelNameFromPayloadKey(i.type),id:i.id===null||i.id===void 0?null:String(i.id)};if(i.attributes&&(e.attributes={...i.attributes}),i.relationships){const d={};for(const[l,s]of Object.entries(i.relationships))s.data===null?d[l]={data:null}:Array.isArray(s.data)?d[l]={data:s.data.map(o=>({type:this.modelNameFromPayloadKey(o.type),id:String(o.id)}))}:d[l]={data:{type:this.modelNameFromPayloadKey(s.data.type),id:String(s.data.id)}};e.relationships=d}return e}normalizeResponse(t,n,r,a,i){if(!r||typeof r!="object")return{data:null};const e=r;let d=null;e.data===null||e.data===void 0?d=null:Array.isArray(e.data)?d=e.data.map(s=>this.normalize(t,n,s)).filter(s=>s!==null):d=this.normalize(t,n,e.data);const l={data:d};if(e.included&&e.included.length>0){const s=[];for(const o of e.included){const u={modelName:this.modelNameFromPayloadKey(o.type),attributes:new Map,relationships:new Map},p=this.normalize(t,u,o);p&&s.push(p)}l.included=s}return e.meta&&(l.meta=e.meta),e.links&&(l.links=e.links),l}serialize(t,n){const r={};t.eachAttribute(e=>{r[this.keyForAttribute(e)]=t.attr(e)});const a={};t.eachRelationship((e,d)=>{const{name:l}=d,s=this.keyForRelationship(l),o=this.payloadKeyFromModelName(d.type);if(d.kind==="belongsTo"){const u=t.belongsTo(l);a[s]=u&&u.id!=null?{data:{type:o,id:String(u.id)}}:{data:null}}else{const u=t.hasMany(l)??[];a[s]={data:u.map(p=>({type:o,id:String(p.id)}))}}});const i={type:this.payloadKeyFromModelName(t.modelName),attributes:r};return n!=null&&n.includeId&&t.id!==null&&(i.id=t.id),Object.keys(a).length>0&&(i.relationships=a),{data:i}}};exports.JsonApiSerializer=_([m.injectable()],exports.JsonApiSerializer);
|
|
2
|
+
//# sourceMappingURL=JsonApiSerializer-CKB02AgP.cjs.map
|