This repository has been archived by the owner on Apr 17, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 73
/
DataSyncPlugin.ts
216 lines (179 loc) · 7.49 KB
/
DataSyncPlugin.ts
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
import { SchemaComposer } from 'graphql-compose';
import { IResolvers, IFieldResolver } from '@graphql-tools/utils';
import { GraphQLNonNull, GraphQLSchema, buildSchema, GraphQLResolveInfo, GraphQLInt, GraphQLBoolean, GraphQLList } from 'graphql';
import { GraphbackCoreMetadata, GraphbackPlugin, ModelDefinition, getInputTypeName, GraphbackOperationType, GraphbackContext, GraphbackTimestamp } from '@graphback/core';
import { getDeltaType, getDeltaListType, getDeltaQuery } from "./deltaMappingHelper";
import { isDataSyncService, isDataSyncModel, DataSyncFieldNames, GlobalConflictConfig, getModelConfigFromGlobal } from "./util";
export const DATASYNC_PLUGIN_NAME = "DataSyncPlugin";
export interface DataSyncPluginConfig {
conflictConfig: GlobalConflictConfig
}
/**
* DataSync plugin
*
* Plugin is enabled by """ @datasync """ annotation
* It will generate delta queries
*/
export class DataSyncPlugin extends GraphbackPlugin {
protected config: DataSyncPluginConfig;
public constructor(config?: DataSyncPluginConfig) {
super()
this.config = {
conflictConfig: {},
...config
};
}
public transformSchema(metadata: GraphbackCoreMetadata): GraphQLSchema {
const schema = metadata.getSchema()
const schemaComposer = new SchemaComposer(schema);
if (!schemaComposer.has(GraphbackTimestamp.name)) {
schemaComposer.createScalarTC(GraphbackTimestamp);
}
const models = metadata.getModelDefinitions();
if (models.length === 0) {
this.logWarning("Provided schema has no models. Returning original schema without any changes.")
return schema;
}
const modelConflictConfigSet = new Set(Object.keys(this.config.conflictConfig?.models || {}))
let dataSyncModelCount = 0;
models.forEach((model: ModelDefinition) => {
// Diff queries
if (isDataSyncModel(model)) {
dataSyncModelCount += 1;
modelConflictConfigSet.delete(model.graphqlType.name);
this.addDataSyncFieldsToModel(schemaComposer, model);
this.addDataSyncFieldsToInputTypes(schemaComposer, model);
this.addDeltaQuery(schemaComposer, model);
}
})
if (dataSyncModelCount === 0) {
// eslint-disable-next-line no-console
console.warn("No DataSync Models detected, ensure that your models are properly annotated.")
}
if (modelConflictConfigSet.size !== 0) {
// eslint-disable-next-line no-console
console.info(`The following models from conflictConfig could not be found, consider adding them to the schema and/or adding the @datasync annotation if you have not done so:\n${Array.from(modelConflictConfigSet).join('\n')} `);
}
return buildSchema(schemaComposer.toSDL())
}
/**
* Creates resolvers for Data Synchonization
*
* @param {GraphbackCoreMetadata} metadata - Core metatata containing all model information
*/
public createResolvers(metadata: GraphbackCoreMetadata): IResolvers {
const models = metadata.getModelDefinitions()
if (models.length === 0) {
return undefined;
}
const resolvers: IResolvers = {}
for (const model of models) {
// If delta marker is encountered, add resolver for `delta` query
if (isDataSyncModel(model)) {
this.addDeltaSyncResolver(model, resolvers)
}
}
return resolvers
}
public createResources(metadata: GraphbackCoreMetadata): void {
// TODO generate delta resolvers
// TODO DataSource support for deltas
// Schema plugin is going to create schema for us
// No work to be done
}
public getPluginName() {
return DATASYNC_PLUGIN_NAME;
}
protected addDeltaSyncResolver(model: ModelDefinition, resolvers: IResolvers) {
const modelName = model.graphqlType.name;
const deltaQuery = getDeltaQuery(modelName)
if (!resolvers.Query) {
resolvers.Query = {} as IFieldResolver<any, any>
}
resolvers.Query[deltaQuery] = async (_: any, args: any, context: GraphbackContext, info: GraphQLResolveInfo) => {
if (!context.graphback || !context.graphback[modelName]) {
throw new Error(`Missing service for ${modelName}`);
}
const dataSyncService = isDataSyncService(context.graphback[modelName]);
if (dataSyncService === undefined) {
throw Error("Service is not a DataSyncCRUDService. Please use DataSyncCRUDService and DataSync-compliant DataProvider with DataSync Plugin to get Delta Queries.")
}
return dataSyncService.sync(args.lastSync, info, args.filter, args.limit);
}
}
protected addDataSyncFieldsToModel(schemaComposer: SchemaComposer<any>, model: ModelDefinition) {
const name = model.graphqlType.name;
const modelTC = schemaComposer.getOTC(name);
const TimestampSTC = schemaComposer.getSTC(GraphbackTimestamp.name);
modelTC.addFields({
[DataSyncFieldNames.lastUpdatedAt]: {
type: TimestampSTC.getType(),
description: "@index(name: 'Datasync_lastUpdatedAt')"
}
});
const modelUsesVersion = getModelConfigFromGlobal(model.graphqlType.name, this.config.conflictConfig).enabled;
if (modelUsesVersion) {
modelTC.addFields({
[DataSyncFieldNames.version]: {
type: GraphQLInt
}
});
}
}
protected addDataSyncFieldsToInputTypes(schemaComposer: SchemaComposer<any>, model: ModelDefinition) {
// Add _version argument to UpdateInputType
const updateInputType = schemaComposer.getITC(getInputTypeName(model.graphqlType.name, GraphbackOperationType.UPDATE));
const modelUsesVersion = getModelConfigFromGlobal(model.graphqlType.name, this.config.conflictConfig).enabled;
if (modelUsesVersion && updateInputType) {
updateInputType.addFields({
[DataSyncFieldNames.version]: {
type: GraphQLNonNull(GraphQLInt)
}
});
}
}
protected addDeltaQuery(schemaComposer: SchemaComposer<unknown>, model: ModelDefinition) {
// Create Delta Type
const modelName = model.graphqlType.name;
const modelTC = schemaComposer.getOTC(modelName);
const updateInputType = schemaComposer.getITC(getInputTypeName(model.graphqlType.name, GraphbackOperationType.UPDATE));
const TimestampSTC = schemaComposer.getSTC(GraphbackTimestamp.name);
// Add Delta Type to schema
const DeltaOTC = schemaComposer.createObjectTC({
name: getDeltaType(modelName),
});
const allFields = Object.values(updateInputType.getType().getFields());
for (const field of allFields) {
DeltaOTC.addFields({ [field.name]: field.type.toString() })
}
DeltaOTC.addFields({
[DataSyncFieldNames.lastUpdatedAt]: {
type: TimestampSTC.getType(),
description: "@index(name: 'Datasync_lastUpdatedAt')"
}
});
DeltaOTC.addFields({
[DataSyncFieldNames.deleted]: GraphQLBoolean
})
// Create and Add Delta List type to schema
const DeltaListOTC = schemaComposer.createObjectTC({
name: getDeltaListType(modelName),
fields: {
items: GraphQLNonNull(GraphQLList(DeltaOTC.getType())),
lastSync: GraphQLNonNull(TimestampSTC.getType()),
limit: GraphQLInt
}
});
// Add Delta Queries
const deltaQuery = getDeltaQuery(model.graphqlType.name);
schemaComposer.Query.addFields({
[deltaQuery]: GraphQLNonNull(DeltaListOTC.getType())
});
const findFilterITC = schemaComposer.getITC(getInputTypeName(modelName, GraphbackOperationType.FIND));
schemaComposer.Query.addFieldArgs(deltaQuery, {
lastSync: GraphQLNonNull(TimestampSTC.getType()),
filter: findFilterITC.getType(),
limit: GraphQLInt
});
}
}