-
Notifications
You must be signed in to change notification settings - Fork 50
Expand file tree
/
Copy pathfetch.ts
More file actions
61 lines (51 loc) · 1.89 KB
/
fetch.ts
File metadata and controls
61 lines (51 loc) · 1.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import QueryBuilder from "../graphql/query-builder";
import Context from "../common/context";
import { Store } from "../orm/store";
import Transformer from "../graphql/transformer";
import { ActionParams, Arguments, Data } from "../support/interfaces";
import Action from "./action";
/**
* Fetch action for sending a query. Will be used for Model.fetch().
*/
export default class Fetch extends Action {
/**
* @param {any} state The Vuex state
* @param {DispatchFunction} dispatch Vuex Dispatch method for the model
* @param {ActionParams} params Optional params to send with the query
* @returns {Promise<Data>} The fetched records as hash
*/
public static async call(
{ state, dispatch }: ActionParams,
params?: ActionParams
): Promise<Data> {
const context = Context.getInstance();
const model = this.getModelFromState(state!);
const mockReturnValue = model.$mockHook("fetch", {
filter: params ? params.filter || {} : {}
});
if (mockReturnValue) {
return Store.insertData(mockReturnValue, dispatch!);
}
await context.loadSchema();
// Filter
let filter = {};
if (params && params.filter) {
filter = Transformer.transformOutgoingData(
model,
params.filter as Data,
true,
undefined,
Object.keys(params.filter)
);
}
const bypassCache = params && params.bypassCache;
// When the filter contains an id, we query in singular mode
const multiple: boolean = !filter["id"];
const name: string = context.adapter.getNameForFetch(model, multiple);
const query = QueryBuilder.buildQuery("query", model, name, filter, multiple, multiple);
// Send the request to the GraphQL API
const data = await context.apollo.request(model, query, filter, false, bypassCache as boolean);
// Insert incoming data into the store
return Store.insertData(data, dispatch!);
}
}