This repository has been archived by the owner on Nov 8, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathservice.ts
1140 lines (967 loc) · 34.9 KB
/
service.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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { ExpressHandler, graphiqlExpress, graphqlExpress } from "apollo-server-express";
import { GraphiQLData } from "apollo-server-module-graphiql";
import * as express from "express";
import { execute, GraphQLError, GraphQLScalarType, GraphQLSchema, subscribe } from "graphql";
import { PubSub } from "graphql-subscriptions";
import { makeExecutableSchema } from "graphql-tools";
import { IResolverObject } from "graphql-tools/dist/Interfaces";
import * as LRU from "lru-cache";
import * as moment from "moment";
import * as pluralize from "pluralize";
import { ObjectSchema, ObjectSchemaProperty } from "realm";
import {
AccessToken,
AdminRealm,
BaseRoute,
Cors,
Delete,
errors,
extractPartialInfo,
Get,
isAdminToken,
Next,
Post,
RefreshToken,
Request,
Response,
RosRequest,
Server,
ServerStarted,
Start,
Stop,
Token,
Upgrade,
User,
} from "realm-object-server";
import { SubscriptionServer } from "subscriptions-transport-ws";
import { setTimeout } from "timers";
import * as url from "url";
import { v4 } from "uuid";
interface SchemaTypes {
type: string;
inputType: string;
}
interface PKInfo {
name: string;
type: string;
}
interface PropertySchemaInfo {
propertySchema: string;
inputPropertySchema: string;
pk: PKInfo;
}
interface SubscriptionDetails {
results: Realm.Results<{}>;
realm: Realm;
}
interface GraphQLRequest extends RosRequest {
user: Realm.Sync.User;
}
interface GraphQLContext {
accessToken: Token;
user: Realm.Sync.User;
realm?: Realm;
operationId?: string;
}
/**
* Settings to control the [[GraphQLService]] behavior.
*/
export interface GraphQLServiceSettings {
/**
* Settings controlling the schema caching strategy. If set to `'NoCache'`,
* Realm schemas will not be cached and instead generated on every request.
* This is useful while developing and schemas may change frequently, but
* drastically reduces performance. If not set, or set to a [[SchemaCacheSettings]]
* instance, schemas will be cached.
*/
schemaCacheSettings?: SchemaCacheSettings | "NoCache";
/**
* Disables authentication for graphql endpoints. This may be useful when
* you are developing the app and want a more relaxed exploring experience.
* If you're using studio to explore the graphql API and responses, it will
* handle authentication for you, so there's no need to disable it.
*/
disableAuthentication?: boolean;
/**
* Disables the grahpiql explorer endpoint (`/grahpql/explore`).
*/
disableExplorer?: boolean;
/**
* The number in milliseconds which a Realm will be kept open after a request
* has completed. Higher values mean that more Realms will be kept in the cache,
* drastically improving the response times of requests hitting "warm" Realms.
* This, however, comes at the cost of increased memory usage. If a negative value
* is provided, the realms will never be evicted from the cache. Default is
* 120000 (2 minutes).
*/
realmCacheMaxAge?: number;
/**
* Controls whether the explorer websocket connections will be made over SSL or
* not. If not set, the service will try to infer the correct value from the
* request protocol, but in some cases, a load balancer may terminate https traffic,
* leading to incorrect websocket protocol being used.
*/
forceExplorerSSL?: boolean;
/**
* Controls whether the total count of the objects matched by the query will be
* returned as a property in the query and subscription responses. Default is false.
*/
includeCountInResponses?: boolean;
/**
* Controls whether integers in the schema will be represented as Floats in the GraphQL
* schema. GraphQL's integer type is 32 bit which means that it can't hold values larger
* than 2,147,483,647. Representing them as floats expands the range to 2^53 - 1, but
* prevents tools from properly enforcing type safety. This means that type mismatch
* errors (e.g. a floating point number is passed in a mutation instead of an integer)
* will get thrown further down the stack and may be harder to interpret. Default is false.
*/
presentIntsAsFloatsInSchema?: boolean;
/**
* Controls the suffix used for the model wrapping a collection of objects. By default, it
* is `Collection`. Override this if you have both `Model` and `ModelCollection` classes
* in your Realm.
*/
collectionModelSuffix?: string;
/**
* Controls the suffix used for the model wrapping an input passed into the `updateModel`
* mutation. By default, it is `Input`. Override this if you have both `Model` and `ModelInput`
* classes in your Realm.
*/
inputModelSuffix?: string;
/**
* Controls the name of the model wrapping a named subscription (only present when the
* Realm is opened in query-sync mode). By default, it is `NamedSubscription`. Override
* this if you already have a `NamedSubscription` class in your Realm.
*/
namedSubscriptionModelName?: string;
/**
* Controls the name of the model wrapping the base64 representation of binary properties.
* By default, it is `Base64`. Override this if you already have a `Base64` class in your Realm.
*/
base64ModelName?: string;
}
/**
* Settings controlling the schema caching strategy.
*/
export interface SchemaCacheSettings {
/**
* The number of schemas to keep in the cache. Default is 1000.
*/
max?: number;
/**
* The max age for schemas in cache. Default is infinite.
*/
maxAge?: number;
}
/**
* A service that exposes a GraphQL API for accessing the Realm files.
* Create a new instance and pass it to `BasicServer.addService` before
* calling `BasicServer.start`
*
* @example
* ```
*
* const service = new GraphQLService({
* // Enable schema caching to improve performance
* schemaCacheSettings: {}
* });
*
* server.addService(service);
*
* server.start();
* ```
*/
@BaseRoute("/graphql")
@Cors("/")
export class GraphQLService {
private readonly schemaCache: LRU.Cache<string, GraphQLSchema>;
private readonly disableAuthentication: boolean;
private readonly realmCacheTTL: number;
private readonly disableExplorer: boolean;
private readonly schemaHandlers: { [path: string]: (realm: Realm, event: string, schema: Realm.ObjectSchema[]) => void } = {};
private readonly forceExplorerSSL: boolean | undefined;
private readonly includeCountInResponses: boolean;
private readonly presentIntsAsFloatsInSchema: boolean;
private readonly collectionModelSuffix: string;
private readonly inputModelSuffix: string;
private readonly namedSubscriptionModelName: string;
private readonly base64Type: GraphQLScalarType;
private server: Server;
private subscriptionServer: SubscriptionServer;
private handler: ExpressHandler;
private graphiql: ExpressHandler;
private pubsub: PubSub;
private querySubscriptions: { [id: string]: SubscriptionDetails } = {};
private adminRealm: Realm;
/**
* Creates a new `GraphQLService` instance.
* @param settings Settings, controlling the behavior of the service related
* to caching and authentication.
*/
constructor(settings?: GraphQLServiceSettings) {
settings = settings || {};
if (settings.schemaCacheSettings !== "NoCache") {
this.schemaCache = new LRU({
max: (settings.schemaCacheSettings && settings.schemaCacheSettings.max) || 1000,
maxAge: settings.schemaCacheSettings && settings.schemaCacheSettings.maxAge,
});
}
this.disableAuthentication = settings.disableAuthentication || false;
this.disableExplorer = settings.disableExplorer || false;
this.realmCacheTTL = settings.realmCacheMaxAge || 120000;
this.forceExplorerSSL = settings.forceExplorerSSL;
this.includeCountInResponses = settings.includeCountInResponses || false;
this.presentIntsAsFloatsInSchema = settings.presentIntsAsFloatsInSchema || false;
this.collectionModelSuffix = settings.collectionModelSuffix || "Collection";
this.namedSubscriptionModelName = settings.namedSubscriptionModelName || "NamedSubscription";
this.inputModelSuffix = settings.inputModelSuffix || "Input";
this.base64Type = new GraphQLScalarType({
name: settings.base64ModelName || "Base64",
description: "A base64-encoded binary blob",
serialize(value) {
return Buffer.from(value).toString("base64");
},
parseValue(value) {
return Buffer.from(value, "base64");
},
parseLiteral(ast) {
if (ast.kind === "StringValue") {
return Buffer.from(ast.value, "base64");
}
throw new TypeError(`Expected StringValue literal, but got ${ast.kind}`);
},
});
}
@ServerStarted()
private serverStarted(server: Server) {
this.server = server;
this.pubsub = new PubSub();
const getOperationId = (socket: any, messageId: string) => {
// socket.id is set to a random value in `onOperation`
return `${socket.id}_${messageId}`;
};
this.subscriptionServer = new SubscriptionServer(
{
execute,
subscribe,
onOperationComplete: (socket, messageId) => {
const opid = getOperationId(socket, messageId);
const details = this.querySubscriptions[opid];
if (details) {
details.results.removeAllListeners();
this.closeRealm(details.realm);
delete this.querySubscriptions[opid];
}
},
onOperation: async (message, params, socket) => {
// HACK: socket.realmPath is set in subscriptionHandler to the
// :path route parameter
if (!socket.realmPath) {
throw new GraphQLError('Missing "realmPath" from context. It is required for subscriptions.');
}
socket.id = v4();
const context = params.context as GraphQLContext;
context.operationId = getOperationId(socket, message.id);
context.realm = await this.openRealm(socket.realmPath, context.user);
params.schema = this.getSchema(socket.realmPath, context.realm);
return params;
},
onConnect: async (authPayload, socket): Promise<GraphQLContext> => {
let accessToken: Token;
let user: Realm.Sync.User;
if (!this.disableAuthentication) {
if (!authPayload || !authPayload.token) {
throw new errors.realm.MissingParameters("Missing 'connectionParams.token'.");
}
accessToken = this.server.tokenValidator.parse(authPayload.token);
user = await this.authenticate(accessToken, socket.realmPath);
}
return {
accessToken,
user,
};
},
},
{
noServer: true,
},
);
this.handler = graphqlExpress(async (req: GraphQLRequest, res) => {
let realm: Realm;
res.once("finish", () => {
this.closeRealm(realm);
});
const path = this.getPath(req);
realm = await this.openRealm(path, req.user);
const schema = this.getSchema(path, realm);
const result: {
schema: GraphQLSchema,
context: GraphQLContext,
} = {
schema,
context: {
realm,
accessToken: req.authToken,
user: req.user,
},
};
return result;
});
this.graphiql = graphiqlExpress((req: GraphQLRequest) => {
const path = this.getPath(req);
let protocol: string;
switch (this.forceExplorerSSL) {
case true:
protocol = "wss";
break;
case false:
protocol = "ws";
break;
default:
protocol = req.protocol === "https" ? "wss" : "ws";
break;
}
const result: GraphiQLData = {
endpointURL: `/graphql/${encodeURIComponent(path)}`,
subscriptionsEndpoint: `${protocol}://${req.get("host")}/graphql/${encodeURIComponent(path)}`,
};
const token = req.get("authorization");
if (token) {
result.passHeader = `'Authorization': '${token}'`;
result.websocketConnectionParams = { token };
}
return result;
});
}
@Start()
private async start(server: Server) {
this.adminRealm = await server.openRealm(AdminRealm);
}
@Stop()
private stop() {
this.subscriptionServer.close();
}
@Upgrade("/:path+")
private async subscriptionHandler(req, socket, head) {
const wsServer = this.subscriptionServer.server;
const ws = await new Promise<any>((resolve) => wsServer.handleUpgrade(req, socket, head, resolve));
// HACK: we're putting the realmPath on the socket client
// and resolving it in subscriptionServer.onOperation to
// populate it in the subscription context.
const path = url.parse(req.url).path.replace("/graphql/", "");
ws.realmPath = this.getPath(path);
wsServer.emit("connection", ws, req);
}
@Get("/explore/*")
private async getExplore(@Request() req: GraphQLRequest, @Response() res: express.Response, @Next() next) {
if (this.disableExplorer) {
throw new errors.realm.AccessDenied();
}
await this.authenticateRequest(req);
this.graphiql(req, res, next);
}
@Post("/explore/*")
private async postExplore(@Request() req: GraphQLRequest, @Response() res: express.Response, @Next() next) {
if (this.disableExplorer) {
throw new errors.realm.AccessDenied();
}
await this.authenticateRequest(req);
this.graphiql(req, res, next);
}
@Get("/*")
private async get(@Request() req: GraphQLRequest, @Response() res: express.Response, @Next() next) {
await this.authenticateRequest(req);
this.handler(req, res, next);
}
@Post("/*")
private async post(@Request() req: GraphQLRequest, @Response() res: express.Response, @Next() next) {
await this.authenticateRequest(req);
this.handler(req, res, next);
}
@Delete("/schema/*")
private deleteSchema(@Request() req: GraphQLRequest, @Response() res: express.Response) {
this.authenticateRequest(req);
this.schemaCache.del(this.getPath(req));
res.status(204).send({});
}
private getPath(reqOrPath: GraphQLRequest | string): string {
let path = typeof reqOrPath === "string" ? decodeURIComponent(reqOrPath) : reqOrPath.params["0"];
if (!path.startsWith("/")) {
path = `/${path}`;
}
return path;
}
private async authenticateRequest(req: GraphQLRequest): Promise<void> {
req.user = await this.authenticate(req.authToken, this.getPath(req));
}
/**
* Ensures the user is authenticated.
* @param authToken token as set by the authentication middleware
* @param path the optional path to look for in the access token.
* If not provided, only admin tokens are accepted.
*/
private async authenticate(authToken: Token, path?: string): Promise<Realm.Sync.User> {
if (this.disableAuthentication) {
return undefined;
}
if (!authToken) {
throw new errors.realm.AccessDenied({ detail: "Authorization header is missing." });
}
const accessToken = authToken as AccessToken;
if (!isAdminToken(authToken) && (!path || accessToken.path !== path)) {
throw new errors.realm.InvalidCredentials({ detail: "The access token doesn't grant access to the requested path." });
}
const partialInfo = extractPartialInfo(path);
if (!partialInfo.isPartial) {
// Full Realm - we don't need user impersonation, so just return undefined to
// make RealmFactory use the admin user
return undefined;
}
if (!partialInfo.customIdentifier.startsWith(authToken.identity + "/")) {
// We enforce that users only open their own Realms.
throw new errors.realm.InvalidCredentials({
detail: "The identifier after /__partial/ in the route must match the user Id. Expected: "
+ `'/__partial/${authToken.identity}/*', but got '/__partial/${partialInfo.customIdentifier}'.`,
});
}
// TODO: optimize that - either cache it or check if the Realm exists in the factory.
const adminRealmUser = this.adminRealm.objectForPrimaryKey<User>("User", authToken.identity);
const refreshToken = new RefreshToken({
appId: authToken.appId,
identity: authToken.identity,
isAdmin: (adminRealmUser && adminRealmUser.isAdmin) || false,
expires: moment().add(1, "year").unix(),
});
// TODO: allow internal https traffic.
const authService = await this.server.discovery.waitForService("auth");
const user = Realm.Sync.User.deserialize({
identity: refreshToken.identity,
isAdmin: refreshToken.isAdmin,
refreshToken: refreshToken.sign(this.server.privateKey),
server: `http://${authService.address}:${authService.port}`,
});
return user;
}
private validateAccess(context: GraphQLContext, access: string) {
if (this.disableAuthentication || isAdminToken(context.accessToken)) {
return;
}
const token = context.accessToken as AccessToken;
if (!token || !token.access || token.access.indexOf(access) < 0) {
throw new errors.realm.InvalidCredentials({
title: `The current user doesn't have '${access}' access.`,
});
}
}
private closeRealm(realm: Realm) {
if (!realm) {
return;
}
if (this.realmCacheTTL >= 0) {
setTimeout(() => realm.close(), this.realmCacheTTL);
} else {
realm.close();
}
}
private validateRead(context: GraphQLContext) {
this.validateAccess(context, "download");
}
private validateWrite(context: GraphQLContext) {
this.validateAccess(context, "upload");
}
private getSchema(path: string, realm: Realm): GraphQLSchema {
if (this.schemaCache && this.schemaCache.has(path)) {
return this.schemaCache.get(path);
}
let schema = `\nscalar ${this.base64Type.name}\n`;
const types = new Array<[string, PKInfo]>();
const queryResolver: IResolverObject = {};
const mutationResolver: IResolverObject = {};
const subscriptionResolver: IResolverObject = {};
const partialInfo = extractPartialInfo(path);
for (const obj of realm.schema) {
if (this.isReserved(obj.name)) {
continue;
}
const propertyInfo = this.getPropertySchema(obj);
if (!propertyInfo.propertySchema) {
// If the object doesn't have properties, we don't want it.
continue;
}
types.push([obj.name, propertyInfo.pk]);
schema += `type ${obj.name} { \n${propertyInfo.propertySchema}}\n\n`;
schema += `type ${obj.name}${this.collectionModelSuffix} {
count: Int!
items: [${obj.name}!]
}\n`;
schema += `input ${obj.name}${this.inputModelSuffix} { \n${propertyInfo.inputPropertySchema}}\n\n`;
}
if (types.length === 0) {
throw new Error(`The schema for Realm at path ${path} is empty.`);
}
let query = "type Query {\n";
let mutation = "type Mutation {\n";
let subscription = "type Subscription {\n";
if (partialInfo.isPartial) {
schema += `type ${this.namedSubscriptionModelName} {
name: String,
objectType: String!,
query: String!
}\n`;
schema += `type ${this.namedSubscriptionModelName}${this.collectionModelSuffix} {
count: Int!
items: [${this.namedSubscriptionModelName}!]
}\n`;
query += this.setupListPartialSubscriptions(queryResolver);
mutation += this.setupDeletePartialSubscription(mutationResolver);
}
for (const [type, pk] of types) {
// TODO: this assumes types are PascalCase
const camelCasedType = this.camelcase(type);
const pluralType = this.pluralize(camelCasedType);
query += this.setupGetAllObjects(queryResolver, type, pluralType);
mutation += this.setupAddObject(mutationResolver, type);
mutation += this.setupDeleteObjects(mutationResolver, type);
if (partialInfo.isPartial) {
mutation += this.setupCreatePartialSubscription(mutationResolver, type);
}
subscription += this.setupSubscribeToQuery(subscriptionResolver, type, pluralType);
// If object has PK, we add get by PK and update option.
if (pk) {
query += this.setupGetObjectByPK(queryResolver, type, camelCasedType, pk);
mutation += this.setupUpdateObject(mutationResolver, type);
mutation += this.setupDiffUpdateObject(mutationResolver, type);
mutation += this.setupDeleteObject(mutationResolver, type, pk);
}
}
query += "}\n\n";
mutation += "}\n\n";
subscription += "}";
schema += query;
schema += mutation;
schema += subscription;
const result = makeExecutableSchema({
typeDefs: schema,
resolvers: {
Query: queryResolver,
Mutation: mutationResolver,
Subscription: subscriptionResolver,
[this.base64Type.name]: this.base64Type,
},
});
if (this.schemaCache) {
this.schemaCache.set(path, result);
}
return result;
}
private setupGetAllObjects(queryResolver: IResolverObject, type: string, pluralType: string): string {
queryResolver[pluralType] = (_, args, context: GraphQLContext) => {
this.validateRead(context);
let result = context.realm.objects(type);
if (args.query) {
result = result.filtered(args.query);
}
if (args.sortBy) {
const descending = args.descending || false;
result = result.sorted(args.sortBy, descending);
}
return this.getCollectionResponse(result, args);
};
// TODO: limit sortBy to only valid properties
const responseType = this.includeCountInResponses ? `${type}${this.collectionModelSuffix}` : `[${type}!]`;
return `${pluralType}(query: String, sortBy: String, descending: Boolean, skip: Int, take: Int): ${responseType}\n`;
}
private setupAddObject(mutationResolver: IResolverObject, type: string): string {
mutationResolver[`add${type}`] = (_, args, context: GraphQLContext) => {
this.validateWrite(context);
let result: any;
context.realm.write(() => {
result = context.realm.create(type, args.input);
});
return result;
};
return `add${type}(input: ${type}${this.inputModelSuffix}): ${type}\n`;
}
private setupSubscribeToQuery(subscriptionResolver: IResolverObject, type: string, pluralType: string): string {
subscriptionResolver[pluralType] = {
subscribe: (_, args, context: GraphQLContext) => {
this.validateRead(context);
let result = context.realm.objects(type);
if (args.query) {
result = result.filtered(args.query);
}
if (args.sortBy) {
const descending = args.descending || false;
result = result.sorted(args.sortBy, descending);
}
const opId = context.operationId;
this.querySubscriptions[opId] = {
results: result,
realm: context.realm,
};
result.addListener((collection, change) => {
const payload = {};
payload[pluralType] = this.getCollectionResponse(collection, args);
this.pubsub.publish(opId, payload);
});
return this.pubsub.asyncIterator(opId);
},
};
// TODO: limit sortBy to only valid properties
const responseType = this.includeCountInResponses ? `${type}${this.collectionModelSuffix}` : `[${type}!]`;
return `${pluralType}(query: String, sortBy: String, descending: Boolean, skip: Int, take: Int): ${responseType}\n`;
}
private setupGetObjectByPK(queryResolver: IResolverObject, type: string, camelCasedType: string, pk: PKInfo): string {
queryResolver[camelCasedType] = (_, args, context: GraphQLContext) => {
this.validateRead(context);
return context.realm.objectForPrimaryKey(type, args[pk.name]);
};
return `${camelCasedType}(${pk.name}: ${pk.type}): ${type}\n`;
}
private setupUpdateObject(mutationResolver: IResolverObject, type: string): string {
// TODO: validate that the PK is set
// TODO: validate that object exists, otherwise it's addOrUpdate not just update
mutationResolver[`update${type}`] = (_, args, context: GraphQLContext) => {
this.validateWrite(context);
let result: any;
context.realm.write(() => {
result = context.realm.create(type, args.input, true);
});
return result;
};
return `update${type}(input: ${type}${this.inputModelSuffix}): ${type}\n`;
}
private setupDiffUpdateObject(mutationResolver: IResolverObject, type: string): string {
mutationResolver[`diffUpdate${type}`] = (_, args, context: GraphQLContext) => {
this.validateWrite(context);
try {
const response = this.upsertObject(context, args.input, type);
return response.result;
} catch (err) {
if (context.realm.isInTransaction) {
context.realm.cancelTransaction();
}
throw err;
}
};
return `diffUpdate${type}(input: ${type}${this.inputModelSuffix}): ${type}\n`;
}
private setupDeleteObject(mutationResolver: IResolverObject, type: string, pk: PKInfo): string {
mutationResolver[`delete${type}`] = (_, args, context: GraphQLContext) => {
this.validateWrite(context);
let result: boolean = false;
context.realm.write(() => {
const obj = context.realm.objectForPrimaryKey(type, args[pk.name]);
if (obj) {
context.realm.delete(obj);
result = true;
}
});
return result;
};
return `delete${type}(${pk.name}: ${pk.type}): Boolean\n`;
}
private setupDeleteObjects(mutationResolver: IResolverObject, type: string): string {
const pluralType = this.pluralize(type);
mutationResolver[`delete${pluralType}`] = (_, args, context: GraphQLContext) => {
this.validateWrite(context);
let result: number;
context.realm.write(() => {
let toDelete = context.realm.objects(type);
if (args.query) {
toDelete = toDelete.filtered(args.query);
}
result = toDelete.length;
context.realm.delete(toDelete);
});
return result;
};
return `delete${pluralType}(query: String): Int\n`;
}
private setupCreatePartialSubscription(mutationResolver: IResolverObject, type: string): string {
mutationResolver[`create${type}Subscription`] = async (_, args, context: GraphQLContext) => {
let result = context.realm.objects(type);
if (args.query) {
result = result.filtered(args.query);
}
if (args.sortBy) {
const descending = args.descending || false;
result = result.sorted(args.sortBy, descending);
}
const subscription = args.name ? result.subscribe(args.name) : result.subscribe();
await new Promise((resolve, reject) => {
subscription.addListener((s, state) => {
switch (state) {
case Realm.Sync.SubscriptionState.Complete:
subscription.removeAllListeners();
resolve();
break;
case Realm.Sync.SubscriptionState.Error:
subscription.removeAllListeners();
reject(subscription.error);
break;
}
});
});
return this.getCollectionResponse(result, {});
};
const responseType = this.includeCountInResponses ? `${type}${this.collectionModelSuffix}` : `[${type}!]`;
return `create${type}Subscription(query: String, sortBy: String, descending: Boolean, name: String): ${responseType}\n`;
}
private setupListPartialSubscriptions(queryResolver: IResolverObject): string {
queryResolver.queryBasedSubscriptions = async (_, args, context: GraphQLContext) => {
const result = context.realm.subscriptions(args.name);
return this.getCollectionResponse(result, {});
};
const responseType = this.includeCountInResponses ? `${this.namedSubscriptionModelName}${this.collectionModelSuffix}` : `[${this.namedSubscriptionModelName}!]`;
return `queryBasedSubscriptions(name: String): ${responseType}\n`;
}
private setupDeletePartialSubscription(mutationResolver: IResolverObject): string {
mutationResolver.deleteQueryBasedSubscription = async (_, args, context: GraphQLContext) => {
context.realm.unsubscribe(args.name);
return true;
};
return "deleteQueryBasedSubscription(name: String!): Boolean\n";
}
private upsertObject(
context: GraphQLContext,
newObject: any,
type: string,
shouldBeginTransaction = true,
): {
result: any,
hasChanges: boolean,
} {
const objectSchema = context.realm.schema.find((s) => s.name === type);
const pkName = objectSchema.primaryKey;
const pkValue = newObject[pkName];
let result = context.realm.objectForPrimaryKey(type, pkValue);
let hasChanges = false;
if (shouldBeginTransaction) {
context.realm.beginTransaction();
}
if (!result) {
// TODO: this can be improved by not recreating linked objects
result = context.realm.create(type, newObject, true);
hasChanges = true;
} else {
for (const propertyName of Object.getOwnPropertyNames(objectSchema.properties)) {
if (newObject[propertyName] === undefined || propertyName === pkName) {
continue;
}
const prop = objectSchema.properties[propertyName] as Realm.ObjectSchemaProperty;
switch (prop.type) {
case "object":
const link = this.upsertObject(context, newObject[propertyName], prop.objectType, false);
hasChanges = hasChanges || link.hasChanges;
if (!result[propertyName]._isSameObject(link.result)) {
hasChanges = true;
result[propertyName] = link.result;
}
break;
case "date":
if (!this.datesEqual(result[propertyName], newObject[propertyName])) {
hasChanges = true;
result[propertyName] = newObject[propertyName];
}
break;
case "list":
// TODO do a better diff
hasChanges = true;
result[propertyName] = [];
for (const item of newObject[propertyName]) {
const upserted = this.upsertObject(context, item, prop.objectType, false);
result[propertyName].push(upserted.result);
}
break;
default:
if (result[propertyName] !== newObject[propertyName]) {
hasChanges = true;
result[propertyName] = newObject[propertyName];
}
break;
}
}
}
if (shouldBeginTransaction) {
if (hasChanges) {
context.realm.commitTransaction();
} else {
context.realm.cancelTransaction();
}
}
return {
result,
hasChanges,
};
}
private getPropertySchema(obj: ObjectSchema): PropertySchemaInfo {
let schemaProperties = "";
let inputSchemaProperties = "";
let primaryKey: PKInfo = null;
for (const key in obj.properties) {
if (!obj.properties.hasOwnProperty(key) ||
this.isReserved(key)) {
continue;
}
const prop = obj.properties[key] as ObjectSchemaProperty;
if (prop.type === "linkingObjects") {
continue;
}
const types = this.getTypeString(prop);
if (!types || this.isReserved(types.type)) {
continue;
}
schemaProperties += `${key}: ${types.type}\n`;
inputSchemaProperties += `${key}: ${types.inputType}\n`;
if (key === obj.primaryKey) {
primaryKey = {
name: key,
type: types.type,
};
}
}
return {
propertySchema: schemaProperties,
inputPropertySchema: inputSchemaProperties,
pk: primaryKey,
};
}
private getTypeString(prop: ObjectSchemaProperty): SchemaTypes {
let type: string;
let inputType: string;
switch (prop.type) {
case "object":
type = prop.objectType;
inputType = `${prop.objectType}${this.inputModelSuffix}`;
break;
case "list":
const innerType = this.getPrimitiveTypeString(prop.objectType, prop.optional);
if (this.isReserved(innerType)) {
return undefined;
}
type = `[${innerType}]`;
switch (prop.objectType) {
case "bool":
case "int":
case "float":