From b845b96f88681c9385154f5a04e5a509f10ec31a Mon Sep 17 00:00:00 2001 From: TheoryOfNekomata Date: Sat, 20 Apr 2024 13:25:04 +0800 Subject: [PATCH] Add preliminary resource relationship support Define resource methods for adding relationships to other resources. --- packages/core/src/common/resource.ts | 40 +++++++++++++++++++++------- 1 file changed, 31 insertions(+), 9 deletions(-) diff --git a/packages/core/src/common/resource.ts b/packages/core/src/common/resource.ts index ad08670..6dc8f86 100644 --- a/packages/core/src/common/resource.ts +++ b/packages/core/src/common/resource.ts @@ -13,12 +13,19 @@ export const PATCH_CONTENT_MAP_TYPE: Record = { type CanPatchObject = Record; +export interface Relationship { + objectResource: Resource, + name: string; + // points to object ID + subjectAttr: string; +} + export interface ResourceState< ItemName extends string = string, RouteName extends string = string > { shared: Map; - relationships: Set; + relationships: Map>; itemName: ItemName; routeName: RouteName; canCreate: boolean; @@ -52,12 +59,17 @@ export interface Resource(resource: Resource): this; + relatesTo( + resource: Resource, + relationshipParams: Relationship, + ): this; dataSource?: DataSource; id( newIdAttr: NewIdAttr, params: ResourceIdConfig ): Resource; + addMetadata(id: string, value: unknown): this; + setMetadata(id: string, value: unknown): this; createdAt(n: NewCreatedAtAttr): Resource; updatedAt(n: NewUpdatedAtAttr): Resource; } @@ -65,7 +77,7 @@ export interface Resource(schema: ResourceType['schema']): Resource => { const resourceState = { shared: new Map(), - relationships: new Set(), + relationships: new Map>(), canCreate: false, canFetchCollection: false, canFetchItem: false, @@ -131,10 +143,14 @@ export const resource = ; - fullTextAttrs.add(attrName); - resourceState.shared.set('fullText', fullTextAttrs); + addMetadata(key: string, value: unknown) { + const fullTextAttrs = (resourceState.shared.get(key) ?? new Set()) as Set; + fullTextAttrs.add(value); + this.setMetadata(key, fullTextAttrs); + return this; + }, + setMetadata(key: string, value: unknown) { + resourceState.shared.set(key, value); return this; }, name(n: NewName) { @@ -154,8 +170,14 @@ export const resource = (resource: Resource) { - resourceState.relationships.add(resource); + relatesTo( + objectResource: Resource, + relationshipParams: Relationship, + ) { + resourceState.relationships.set(relationshipParams.name, { + ...relationshipParams, + objectResource, + }); return this; }, createdAt(n: NewCreatedAtAttr) {