Skip to content

Commit ddb43de

Browse files
committed
feat(model): create toJSON/toObject return types
1 parent 51afa6c commit ddb43de

File tree

2 files changed

+39
-5
lines changed

2 files changed

+39
-5
lines changed

src/index.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,12 @@ export {
33
} from './lib/client'
44

55
export {
6+
Json,
67
model,
78
Model,
89
ModelConstructor,
9-
ModelInstance
10+
ModelInstance,
11+
Object
1012
} from './lib/model'
1113

1214
export {

src/lib/model.ts

Lines changed: 36 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,38 @@ import Client, { client } from "./client";
33
import Query, { FilterQuery } from "./query";
44
import Schema from "./schema";
55

6+
type JsonifiedValue<T> =
7+
T extends Model<infer U> ? Json<U> :
8+
T extends Model<infer U>[] ? Json<U>[] :
9+
T extends Date ? string :
10+
T;
11+
12+
export type Json<DocType> = {
13+
/** The JSON:API resource type. */
14+
type: string;
15+
16+
/** The JSON:API resource id. */
17+
id: string;
18+
} & {
19+
[K in keyof DocType]: JsonifiedValue<DocType[K]>;
20+
};
21+
22+
type ObjectifiedValue<T> =
23+
T extends Model<infer U> ? Object<U> :
24+
T extends Model<infer U>[] ? Object<U>[] :
25+
T;
26+
27+
export type Object<DocType> = {
28+
/** The JSON:API resource type. */
29+
type: string;
30+
31+
/** The JSON:API resource id. */
32+
id: string;
33+
} & {
34+
[K in keyof DocType]: ObjectifiedValue<DocType[K]>;
35+
};
36+
37+
638
const models: {
739
[type: string]: ModelConstructor<Record<string, any>>,
840
} = {};
@@ -11,7 +43,7 @@ const models: {
1143
export type ModelConstructor<DocType> = {
1244

1345
new(
14-
obj?: Partial<DocType> | Record<string, any>,
46+
obj?: Partial<DocType> | Partial<Object<DocType>> | Partial<Json<DocType>> | Record<string, any>,
1547
options?: {
1648
isNew?: boolean;
1749
}
@@ -67,7 +99,7 @@ export class Model<DocType> {
6799
this.init(obj, options);
68100
}
69101

70-
assign!: (obj: Partial<DocType> | Record<string, any>) => this;
102+
assign!: (obj: Partial<DocType> | Partial<Object<DocType>> | Partial<Json<DocType>> | Record<string, any>) => this;
71103

72104
copy!: (obj?: Partial<DocType>) => this;
73105

@@ -110,15 +142,15 @@ export class Model<DocType> {
110142
},
111143
) => this;
112144

113-
toJSON!: () => DocType;
145+
toJSON!: () => Json<DocType>;
114146

115147
toJsonApi!: () => JsonApiBody<JsonApiResource>;
116148

117149
toObject!: (
118150
options?: {
119151
transform?: boolean,
120152
},
121-
) => DocType;
153+
) => Object<DocType>;
122154

123155
unmarkModified!: <T extends keyof DocType>(path: T) => void;
124156
}

0 commit comments

Comments
 (0)