Debian Codegraph @

types/tests/overview-test.ts

raw
1 /**
2 * Code samples from the official documentation: "Overview" page
3 */
4 import { belongsTo, Factory, hasMany, Model, Response, Server } from "miragejs";
5
6 new Server({
7 routes() {
8 this.namespace = "api";
9
10 // Responding to a POST request
11 this.post("/movies", (schema, request) => {
12 const attrs = JSON.parse(request.requestBody);
13 attrs.id = Math.floor(Math.random() * 100);
14
15 return { movie: attrs };
16 });
17
18 // Using the `timing` option to slow down the response
19 this.get(
20 "/movies",
21 () => {
22 return {
23 movies: [
24 { id: 1, name: "Inception", year: 2010 },
25 { id: 2, name: "Interstellar", year: 2014 },
26 { id: 3, name: "Dunkirk", year: 2017 },
27 ],
28 };
29 },
30 { timing: 4000 }
31 );
32
33 // Using the `Response` class to return a 500
34 this.delete("/movies/1", () => {
35 const headers = {};
36 const data = { errors: ["Server did not respond"] };
37
38 return new Response(500, headers, data);
39 });
40 },
41 });
42
43 new Server({
44 models: {
45 movie: Model,
46 },
47
48 routes() {
49 this.namespace = "api";
50
51 this.get("/movies", () => {
52 return {
53 movies: [
54 { id: 1, name: "Inception", year: 2010 },
55 { id: 2, name: "Interstellar", year: 2014 },
56 { id: 3, name: "Dunkirk", year: 2017 },
57 ],
58 };
59 });
60 },
61
62 seeds(server) {
63 server.createList("movie", 10);
64 },
65 });
66
67 new Server({
68 models: {
69 movie: Model,
70 },
71
72 routes() {
73 this.namespace = "api";
74
75 this.get("/movies");
76 this.get("/movies/:id");
77 this.post("/movies");
78 this.patch("/movies/:id");
79 this.del("/movies/:id");
80 },
81
82 factories: {
83 movie: Factory.extend({
84 title(i: number) {
85 return `Movie ${i}`; // Movie 1, Movie 2, etc.
86 },
87
88 year() {
89 const min = 1950;
90 const max = 2019;
91
92 return Math.floor(Math.random() * (max - min + 1)) + min;
93 },
94
95 rating: "PG-13",
96 }),
97 },
98 });
99
100 new Server({
101 models: {
102 movie: Model.extend({
103 castMembers: hasMany(),
104 }),
105 castMember: Model.extend({
106 movie: belongsTo(),
107 }),
108 },
109 routes() {
110 this.get("/movies/:id/cast-members", (schema, request) => {
111 const movie = schema.db.movies.find(request.params.id);
112
113 return movie.castMembers;
114 });
115 },
116 });