| 1 |
import { Server, Model, hasMany, belongsTo } from "miragejs"; |
| 2 |
|
| 3 |
/* |
| 4 |
A model with a hasMany association can be in eight states |
| 5 |
with respect to its association. This helper class |
| 6 |
returns a parent (and its children) in these various states. |
| 7 |
|
| 8 |
The return value is an array of the form |
| 9 |
|
| 10 |
[ parent, [child1, child2...] ] |
| 11 |
|
| 12 |
where the children array may be empty. |
| 13 |
*/ |
| 14 |
export default class Helper { |
| 15 |
constructor() { |
| 16 |
this.server = new Server({ |
| 17 |
environment: "test", |
| 18 |
models: { |
| 19 |
user: Model.extend({ |
| 20 |
posts: hasMany(), |
| 21 |
}), |
| 22 |
post: Model.extend({ |
| 23 |
user: belongsTo(), |
| 24 |
}), |
| 25 |
}, |
| 26 |
}); |
| 27 |
|
| 28 |
this.db = this.server.db; |
| 29 |
this.schema = this.server.schema; |
| 30 |
} |
| 31 |
|
| 32 |
shutdown() { |
| 33 |
this.server.shutdown(); |
| 34 |
} |
| 35 |
|
| 36 |
savedChildNoParent() { |
| 37 |
let post = this.db.posts.insert({ title: "Lorem" }); |
| 38 |
|
| 39 |
return [this.schema.posts.find(post.id), null]; |
| 40 |
} |
| 41 |
|
| 42 |
savedChildNewParent() { |
| 43 |
let post = this.schema.posts.create({ title: "Lorem" }); |
| 44 |
let user = this.schema.users.new({ name: "Link" }); |
| 45 |
|
| 46 |
post.user = user; |
| 47 |
|
| 48 |
return [post, user]; |
| 49 |
} |
| 50 |
|
| 51 |
savedChildSavedParent() { |
| 52 |
let { schema } = this; |
| 53 |
schema.db.loadData({ |
| 54 |
posts: [{ id: "1", title: "Lorem", userId: "1" }], |
| 55 |
users: [{ id: "1", name: "Link", postIds: ["1"] }], |
| 56 |
}); |
| 57 |
|
| 58 |
return [schema.posts.find(1), schema.users.find(1)]; |
| 59 |
} |
| 60 |
|
| 61 |
newChildNoParent() { |
| 62 |
let post = this.schema.posts.new({ title: "Lorem" }); |
| 63 |
|
| 64 |
return [post, null]; |
| 65 |
} |
| 66 |
|
| 67 |
newChildNewParent() { |
| 68 |
let post = this.schema.posts.new({ title: "Lorem" }); |
| 69 |
let user = this.schema.users.new({ name: "Link" }); |
| 70 |
|
| 71 |
post.user = user; |
| 72 |
|
| 73 |
return [post, user]; |
| 74 |
} |
| 75 |
|
| 76 |
newChildSavedParent() { |
| 77 |
let post = this.schema.posts.create({ title: "Lorem" }); |
| 78 |
let user = this.schema.users.new({ name: "Link" }); |
| 79 |
|
| 80 |
post.user = user; |
| 81 |
|
| 82 |
return [post, user]; |
| 83 |
} |
| 84 |
|
| 85 |
// Unassociated models |
| 86 |
savedParent() { |
| 87 |
let insertedUser = this.db.users.insert({ name: "Link" }); |
| 88 |
|
| 89 |
return this.schema.users.find(insertedUser.id); |
| 90 |
} |
| 91 |
|
| 92 |
newParent() { |
| 93 |
return this.schema.users.new({ name: "Link" }); |
| 94 |
} |
| 95 |
} |
| 96 |
|
| 97 |
export const states = [ |
| 98 |
"savedChildNoParent", |
| 99 |
"savedChildNewParent", |
| 100 |
"savedChildSavedParent", |
| 101 |
"newChildNoParent", |
| 102 |
"newChildNewParent", |
| 103 |
"newChildSavedParent", |
| 104 |
]; |