data-client
data-client copied to clipboard
Use an existing class for a resource
Hello,
I have a normal class, can I use it to create a resource? Something like this?
export class Demo {
id: number,
value: string
}
export default class DemoResource extends Resource<Demo> {
pk() {
return this.id?.toString();
}
static urlRoot = 'http://test.com/demo/';
}
Since JavaScript does not have multiple inheritance, and you need Resource, you cannot do this out of the box. You could try doing a mixin pattern but that does weird things to types so I'm not sure how useful it will be.
If you want to use a different class pattern - you don't need to use Resource or even Entity. All you need to do to get normalization is build something that complies with EntityInterface.
export interface EntityInterface<T = any> extends SchemaSimple {
pk(params: any, parent?: any, key?: string): string | undefined;
readonly key: string;
merge(existing: any, incoming: any): any;
schema: Record<string, Schema>;
prototype: T;
}
Then you could also define Endpoint separately instead of including them in the class itself (since you want to use another class).
This may be a pattern other people may want, so if you're interested, we'd be happy on giving guidance to craft a PR for a @rest-hooks/something
addition here.