Debian Codegraph @

types/tests/relationships-test.ts

raw
1 import { belongsTo, hasMany, Model, Registry } from "miragejs";
2 import Schema from "miragejs/orm/schema";
3
4 const PersonModel = Model.extend({
5 name: "hello",
6 parent: belongsTo("person"),
7 pets: hasMany("pet"),
8 friends: hasMany<"pet" | "person">({ polymorphic: true }),
9
10 nothing: belongsTo("nonexistent"),
11 muchAdoAboutNothing: hasMany("nonexistent"),
12 });
13
14 const PetModel = Model.extend({
15 name: "fido",
16 owner: belongsTo("person"),
17 });
18
19 type PersonRegistry = Registry<
20 { person: typeof PersonModel; pet: typeof PetModel },
21 {}
22 >;
23 declare const schema: Schema<PersonRegistry>;
24
25 const people = schema.all("person");
26
27 people.length; // $ExpectType number
28 people.modelName; // $ExpectType string
29 people.models.map((model) => {
30 model.nothing; // $ExpectType unknown
31 model.muchAdoAboutNothing; // $ExpectType Collection<unknown>
32
33 model.parent?.name; // $ExpectType string | undefined
34 model.parent?.parent?.name; // $ExpectType string | undefined
35 model.pets.models[0].name; // $ExpectType string
36
37 // Polymorphic relationship
38 const friend = model.friends.models[0];
39
40 // Both 'pet' and 'person' models have a name, but no other shared fields
41 friend.name; // $ExpectType string
42 friend.parent; // $ExpectError
43 friend.friends; // $ExpectError
44 friend.owner; // $ExpectError
45
46 if ("parent" in friend) {
47 // Here we know friend is a person
48 friend.parent!.name; // $ExpectType string
49 friend.friends.length; // $ExpectType number
50 } else {
51 // Here we know friend is a pet
52 friend.owner!.name; // $ExpectType string
53 }
54 });
55
56 const child = schema.create("person", {
57 parent: schema.create("person"),
58 });
59
60 // Here we know `parent` is defined because it was just passed in
61 child.parent.name; // $ExpectType string
62
63 schema.create("person", { parent: "hi" }); // $ExpectError
64
65 const pet1 = schema.create("pet");
66 const pet2 = schema.create("pet");
67
68 // We can instantiate a hasMany with either an array or a collection
69 // Either way, the instance should have a collection.
70
71 const personWithPetsArray = schema.create("person", {
72 pets: [pet1, pet2],
73 });
74
75 personWithPetsArray.pets.modelName; // $ExpectType string
76
77 const personWithPetsCollection = schema.create("person", {
78 pets: schema.all("pet"),
79 });
80
81 personWithPetsCollection.pets.modelName; // $ExpectType string
82
83 schema.create("person", { pets: [child] }); // $ExpectError
84 schema.create("person", { pets: schema.all("person") }); // $ExpectError