@webresto/graphql 1.3.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (105) hide show
  1. package/.editorconfig +10 -0
  2. package/index.d.ts +3 -0
  3. package/index.js +22 -0
  4. package/index.ts +14 -0
  5. package/lib/afterHook.d.ts +1 -0
  6. package/lib/afterHook.js +24 -0
  7. package/lib/afterHook.ts +26 -0
  8. package/lib/afterHook.ts___graphql-transport-ws +138 -0
  9. package/lib/afterHook.ts___graphql-ws +133 -0
  10. package/lib/defaults.js +12 -0
  11. package/lib/errorWrapper.d.ts +4 -0
  12. package/lib/errorWrapper.js +13 -0
  13. package/lib/errorWrapper.ts +12 -0
  14. package/lib/eventHelper.d.ts +21 -0
  15. package/lib/eventHelper.js +32 -0
  16. package/lib/eventHelper.ts +35 -0
  17. package/lib/graphqlHelper.d.ts +115 -0
  18. package/lib/graphqlHelper.js +596 -0
  19. package/lib/graphqlHelper.ts +692 -0
  20. package/lib/initialize.d.ts +1 -0
  21. package/lib/initialize.js +22 -0
  22. package/lib/initialize.ts +21 -0
  23. package/notes.md +1976 -0
  24. package/package.json +47 -0
  25. package/readme.md +258 -0
  26. package/restApi.http +11 -0
  27. package/src/additionalResolvers.d.ts +19 -0
  28. package/src/additionalResolvers.js +114 -0
  29. package/src/additionalResolvers.ts +111 -0
  30. package/src/graphql.d.ts +7 -0
  31. package/src/graphql.js +144 -0
  32. package/src/graphql.ts +160 -0
  33. package/src/resolvers/cart.d.ts +123 -0
  34. package/src/resolvers/cart.js +176 -0
  35. package/src/resolvers/cart.ts +256 -0
  36. package/src/resolvers/checkout.d.ts +30 -0
  37. package/src/resolvers/checkout.js +226 -0
  38. package/src/resolvers/checkout.ts +242 -0
  39. package/src/resolvers/dishAndModifier.d.ts +2 -0
  40. package/src/resolvers/dishAndModifier.js +35 -0
  41. package/src/resolvers/dishAndModifier.ts +38 -0
  42. package/src/resolvers/maintenance.d.ts +9 -0
  43. package/src/resolvers/maintenance.js +12 -0
  44. package/src/resolvers/maintenance.ts +11 -0
  45. package/src/resolvers/paymentMethod.d.ts +9 -0
  46. package/src/resolvers/paymentMethod.js +22 -0
  47. package/src/resolvers/paymentMethod.ts +20 -0
  48. package/src/resolvers/restrictions.d.ts +9 -0
  49. package/src/resolvers/restrictions.js +24 -0
  50. package/src/resolvers/restrictions.ts +22 -0
  51. package/src/resolvers/streets.d.ts +9 -0
  52. package/src/resolvers/streets.js +16 -0
  53. package/src/resolvers/streets.ts +13 -0
  54. package/src/resolvers/subscriptions.d.ts +33 -0
  55. package/src/resolvers/subscriptions.js +52 -0
  56. package/src/resolvers/subscriptions.ts +63 -0
  57. package/test/.eslintrc +8 -0
  58. package/test/_bootstrap.js +29 -0
  59. package/test/fixtures/v0.12-app/.gitignore +11 -0
  60. package/test/fixtures/v0.12-app/.sailsrc +11 -0
  61. package/test/fixtures/v0.12-app/api/controllers/.gitkeep +0 -0
  62. package/test/fixtures/v0.12-app/api/models/.gitkeep +0 -0
  63. package/test/fixtures/v0.12-app/api/models/TestModel.js +22 -0
  64. package/test/fixtures/v0.12-app/api/responses/badRequest.js +76 -0
  65. package/test/fixtures/v0.12-app/api/responses/created.js +60 -0
  66. package/test/fixtures/v0.12-app/api/responses/forbidden.js +89 -0
  67. package/test/fixtures/v0.12-app/api/responses/notFound.js +94 -0
  68. package/test/fixtures/v0.12-app/api/responses/ok.js +60 -0
  69. package/test/fixtures/v0.12-app/api/responses/serverError.js +89 -0
  70. package/test/fixtures/v0.12-app/api/services/.gitkeep +0 -0
  71. package/test/fixtures/v0.12-app/app.js +73 -0
  72. package/test/fixtures/v0.12-app/config/bootstrap.js +6 -0
  73. package/test/fixtures/v0.12-app/config/connections.js +5 -0
  74. package/test/fixtures/v0.12-app/config/cors.js +78 -0
  75. package/test/fixtures/v0.12-app/config/csrf.js +64 -0
  76. package/test/fixtures/v0.12-app/config/env/development.js +10 -0
  77. package/test/fixtures/v0.12-app/config/env/production.js +16 -0
  78. package/test/fixtures/v0.12-app/config/globals.js +63 -0
  79. package/test/fixtures/v0.12-app/config/hookTimeout.js +8 -0
  80. package/test/fixtures/v0.12-app/config/http.js +93 -0
  81. package/test/fixtures/v0.12-app/config/i18n.js +57 -0
  82. package/test/fixtures/v0.12-app/config/log.js +29 -0
  83. package/test/fixtures/v0.12-app/config/models.js +3 -0
  84. package/test/fixtures/v0.12-app/config/policies.js +51 -0
  85. package/test/fixtures/v0.12-app/config/restoapi.js +3 -0
  86. package/test/fixtures/v0.12-app/config/restocore.js +39 -0
  87. package/test/fixtures/v0.12-app/config/routes.js +49 -0
  88. package/test/fixtures/v0.12-app/config/session.js +100 -0
  89. package/test/fixtures/v0.12-app/config/sockets.js +141 -0
  90. package/test/fixtures/v0.12-app/config/stateflow.js +4 -0
  91. package/test/fixtures/v0.12-app/config/views.js +95 -0
  92. package/test/fixtures/v0.12-app/package.json +34 -0
  93. package/test/fixtures/v0.12-app/views/403.ejs +68 -0
  94. package/test/fixtures/v0.12-app/views/404.ejs +68 -0
  95. package/test/fixtures/v0.12-app/views/500.ejs +73 -0
  96. package/test/fixtures/v0.12-app/views/homepage.ejs +74 -0
  97. package/test/fixtures/v0.12-app/views/layout.ejs +91 -0
  98. package/test/mocha.opts +2 -0
  99. package/test/readme.md +0 -0
  100. package/test/todo +0 -0
  101. package/test/tslint.json +18 -0
  102. package/test/unit/first.test.js +11 -0
  103. package/test/unit/sails_not_crash.test.js +3 -0
  104. package/todo.md +1 -0
  105. package/tsconfig.json +10 -0
package/src/graphql.js ADDED
@@ -0,0 +1,144 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const helper = require("../lib/graphqlHelper");
4
+ const getEmitter_1 = require("@webresto/core/libs/getEmitter");
5
+ const _ = require("lodash");
6
+ const additionalResolvers_1 = require("./additionalResolvers");
7
+ const { ApolloServer } = require('apollo-server-express');
8
+ const fs = require('fs');
9
+ const path = require('path');
10
+ const { PubSub } = require('apollo-server');
11
+ const pubsub = new PubSub();
12
+ sails.graphql = { pubsub };
13
+ let server;
14
+ const AdditionalResolvers = {};
15
+ exports.default = {
16
+ getPubsub: () => pubsub,
17
+ getServer: () => server,
18
+ addAdditionalResolver: (resolver) => {
19
+ _.merge(AdditionalResolvers, resolver);
20
+ },
21
+ init: async function () {
22
+ var _a, _b;
23
+ let resolversApiPath = path.resolve(__dirname, './resolvers');
24
+ if (fs.existsSync(resolversApiPath)) {
25
+ helper.addDirResolvers(resolversApiPath);
26
+ }
27
+ resolversApiPath = path.resolve(process.cwd(), "./api/resolvers");
28
+ if (fs.existsSync(resolversApiPath)) {
29
+ helper.addDirResolvers(resolversApiPath);
30
+ }
31
+ helper.addAllSailsModels();
32
+ if ((_a = sails.config.restographql) === null || _a === void 0 ? void 0 : _a.whiteListAutoGen)
33
+ helper.setWhiteList(sails.config.restographql.whiteListAutoGen);
34
+ if ((_b = sails.config.restographql) === null || _b === void 0 ? void 0 : _b.blackList)
35
+ helper.addToBlackList(sails.config.restographql.blackList);
36
+ // console.dir(autoGenerate, {depth: null});
37
+ _.merge(AdditionalResolvers, additionalResolvers_1.additionalResolver);
38
+ helper.addType(`
39
+
40
+ input Customer {
41
+ phone: Phone
42
+ mail: String
43
+ name: String!
44
+ }
45
+ input Phone {
46
+ code: String!
47
+ number: String!
48
+ additionalNumber: String
49
+ }
50
+ input Address {
51
+ streetId: String
52
+ home: String
53
+ comment: String
54
+ city: String
55
+ street: String
56
+ housing: String
57
+ index: String
58
+ entrance: String
59
+ floor: String
60
+ apartment: String
61
+ doorphone: String
62
+ }
63
+ type Message {
64
+ title: String
65
+ type: String
66
+ message: String
67
+ }
68
+ type Action {
69
+ type: String
70
+ data: Json
71
+ }
72
+ type CheckResponse {
73
+ order: Order
74
+ message: Message
75
+ action: Action
76
+ }
77
+ type GetOrderResponse {
78
+ order: Order
79
+ customData: Json
80
+ }
81
+ type Restrictions {
82
+ workTime: Json
83
+ periodPossibleForOrder: Json
84
+ timezone: Json
85
+ deliveryDescription: Json
86
+ minDeliveryTime: Json
87
+ }
88
+ `);
89
+ // helper.addToBlackList(["createdAt", "updatedAt"]);
90
+ // required root types for moduling schema
91
+ helper.addType(`
92
+ type Query {
93
+ _root: String
94
+ }
95
+ type Mutation {
96
+ _root: String
97
+ }
98
+ type Subscription {
99
+ _root: String
100
+ }`);
101
+ const { typeDefs, resolvers } = helper.getSchema();
102
+ getEmitter_1.default().on('core-order-after-count', 'graphql', function (order) {
103
+ pubsub.publish("order-changed", order);
104
+ });
105
+ getEmitter_1.default().on("send-message", "graphql", function ({ orderId, message }) {
106
+ pubsub.publish("message", { orderId, message });
107
+ });
108
+ getEmitter_1.default().on("core-dish-after-update", "graphql", function (record) {
109
+ pubsub.publish("dish-changed", record);
110
+ });
111
+ getEmitter_1.default().on("core-maintenance-enabled", "graphql", function (record) {
112
+ pubsub.publish("maintenance", record);
113
+ });
114
+ getEmitter_1.default().on("core-maintenance-disabled", "graphql", function () {
115
+ pubsub.publish("maintenance", null);
116
+ });
117
+ const apolloServer = new ApolloServer({
118
+ typeDefs,
119
+ resolvers: [resolvers, AdditionalResolvers],
120
+ subscriptions: {
121
+ onConnect: (connectionParams, webSocket) => {
122
+ let exContext = {};
123
+ if (connectionParams) {
124
+ if (!connectionParams['authorization'] && connectionParams['Authorization'])
125
+ connectionParams['authorization'] = connectionParams['Authorization'];
126
+ exContext['connectionParams'] = connectionParams;
127
+ }
128
+ exContext['pubsub'] = pubsub;
129
+ return exContext;
130
+ },
131
+ },
132
+ context: async ({ req, connection }) => {
133
+ if (connection) {
134
+ return connection.context;
135
+ }
136
+ else {
137
+ return { ...req };
138
+ }
139
+ }
140
+ });
141
+ server = apolloServer;
142
+ return apolloServer;
143
+ }
144
+ };
package/src/graphql.ts ADDED
@@ -0,0 +1,160 @@
1
+ import * as helper from '../lib/graphqlHelper';
2
+ import getEmitter from "@webresto/core/libs/getEmitter";
3
+ import _ = require("lodash");
4
+ import { additionalResolver } from './additionalResolvers';
5
+
6
+ const { ApolloServer } = require('apollo-server-express');
7
+ const fs = require('fs');
8
+ const path = require('path');
9
+
10
+ const { PubSub } = require('apollo-server');
11
+ const pubsub = new PubSub();
12
+ sails.graphql = { pubsub };
13
+ let server;
14
+
15
+ const AdditionalResolvers: any = {
16
+ }
17
+
18
+ export default {
19
+ getPubsub: () => pubsub,
20
+ getServer: () => server,
21
+ addAdditionalResolver: (resolver) => {
22
+ _.merge(AdditionalResolvers, resolver);
23
+ },
24
+ init: async function () {
25
+ let resolversApiPath = path.resolve(__dirname, './resolvers');
26
+ if (fs.existsSync(resolversApiPath)) {
27
+ helper.addDirResolvers(resolversApiPath);
28
+ }
29
+ resolversApiPath = path.resolve(process.cwd(), "./api/resolvers");
30
+ if (fs.existsSync(resolversApiPath)) {
31
+ helper.addDirResolvers(resolversApiPath);
32
+ }
33
+
34
+ helper.addAllSailsModels();
35
+
36
+ if (sails.config.restographql?.whiteListAutoGen)
37
+ helper.setWhiteList(
38
+ sails.config.restographql.whiteListAutoGen
39
+ );
40
+
41
+ if (sails.config.restographql?.blackList)
42
+ helper.addToBlackList(sails.config.restographql.blackList);
43
+ // console.dir(autoGenerate, {depth: null});
44
+
45
+ _.merge(AdditionalResolvers, additionalResolver);
46
+
47
+ helper.addType(`
48
+
49
+ input Customer {
50
+ phone: Phone
51
+ mail: String
52
+ name: String!
53
+ }
54
+ input Phone {
55
+ code: String!
56
+ number: String!
57
+ additionalNumber: String
58
+ }
59
+ input Address {
60
+ streetId: String
61
+ home: String
62
+ comment: String
63
+ city: String
64
+ street: String
65
+ housing: String
66
+ index: String
67
+ entrance: String
68
+ floor: String
69
+ apartment: String
70
+ doorphone: String
71
+ }
72
+ type Message {
73
+ title: String
74
+ type: String
75
+ message: String
76
+ }
77
+ type Action {
78
+ type: String
79
+ data: Json
80
+ }
81
+ type CheckResponse {
82
+ order: Order
83
+ message: Message
84
+ action: Action
85
+ }
86
+ type GetOrderResponse {
87
+ order: Order
88
+ customData: Json
89
+ }
90
+ type Restrictions {
91
+ workTime: Json
92
+ periodPossibleForOrder: Json
93
+ timezone: Json
94
+ deliveryDescription: Json
95
+ minDeliveryTime: Json
96
+ }
97
+ `);
98
+
99
+
100
+ // helper.addToBlackList(["createdAt", "updatedAt"]);
101
+
102
+ // required root types for moduling schema
103
+ helper.addType(`
104
+ type Query {
105
+ _root: String
106
+ }
107
+ type Mutation {
108
+ _root: String
109
+ }
110
+ type Subscription {
111
+ _root: String
112
+ }`);
113
+
114
+ const { typeDefs, resolvers } = helper.getSchema();
115
+
116
+ getEmitter().on('core-order-after-count', 'graphql', function (order) {
117
+ pubsub.publish("order-changed", order);
118
+ });
119
+ getEmitter().on("send-message", "graphql", function ({ orderId, message }) {
120
+ pubsub.publish("message", { orderId, message });
121
+ });
122
+ getEmitter().on("core-dish-after-update", "graphql", function (record) {
123
+ pubsub.publish("dish-changed", record);
124
+ });
125
+ getEmitter().on("core-maintenance-enabled", "graphql", function (record) {
126
+ pubsub.publish("maintenance", record);
127
+ });
128
+ getEmitter().on("core-maintenance-disabled", "graphql", function () {
129
+ pubsub.publish("maintenance", null);
130
+ });
131
+
132
+ const apolloServer = new ApolloServer({
133
+ typeDefs,
134
+ resolvers: [resolvers, AdditionalResolvers],
135
+ subscriptions: {
136
+ onConnect: (connectionParams, webSocket) => {
137
+ let exContext = {}
138
+ if (connectionParams) {
139
+ if (!connectionParams['authorization'] && connectionParams['Authorization'])
140
+ connectionParams['authorization'] = connectionParams['Authorization'];
141
+
142
+ exContext['connectionParams'] = connectionParams
143
+ }
144
+ exContext['pubsub'] = pubsub;
145
+ return exContext;
146
+ },
147
+ },
148
+ context: async ({ req , connection}) => {
149
+ if (connection) {
150
+ return connection.context;
151
+ } else {
152
+ return { ...req };
153
+ }
154
+ }
155
+ });
156
+
157
+ server = apolloServer;
158
+ return apolloServer;
159
+ }
160
+ }
@@ -0,0 +1,123 @@
1
+ declare const _default: {
2
+ Query: {
3
+ order: {
4
+ def: string;
5
+ fn: (parent: any, args: any, context: any) => Promise<{
6
+ id: string;
7
+ shortId: string;
8
+ dishes: number[] | import("@webresto/core/models/OrderDish").default[];
9
+ discount: any;
10
+ paymentMethod: any;
11
+ paymentMethodTitle: string;
12
+ paid: {
13
+ type: string;
14
+ defaultsTo: boolean;
15
+ };
16
+ isPaymentPromise: boolean;
17
+ dishesCount: number;
18
+ uniqueDishes: number;
19
+ modifiers: any;
20
+ customer: any;
21
+ address: any;
22
+ comment: string;
23
+ personsCount: string;
24
+ date: string;
25
+ problem: boolean;
26
+ rmsDelivered: boolean;
27
+ rmsId: string;
28
+ rmsOrderNumber: string;
29
+ rmsOrderData: any;
30
+ rmsDeliveryDate: string;
31
+ rmsErrorMessage: string;
32
+ rmsErrorCode: string;
33
+ rmsStatusCode: string;
34
+ deliveryStatus: string;
35
+ selfService: boolean;
36
+ deliveryDescription: string;
37
+ message: string;
38
+ deliveryItem: any;
39
+ deliveryCost: number;
40
+ totalWeight: number;
41
+ total: number;
42
+ trifleFrom: number;
43
+ orderTotal: number;
44
+ discountTotal: number;
45
+ orderDate: string;
46
+ customData: any;
47
+ state: string;
48
+ toJSON(): any;
49
+ }>;
50
+ };
51
+ };
52
+ Mutation: {
53
+ orderAddDish: {
54
+ def: string;
55
+ fn: (parent: any, args: any, context: any) => Promise<import("@webresto/core/models/Order").default>;
56
+ };
57
+ orderReplaceDish: {
58
+ def: string;
59
+ fn: (parent: any, args: any, context: any) => Promise<import("@webresto/core/models/Order").default>;
60
+ };
61
+ orderRemoveDish: {
62
+ def: string;
63
+ fn: (parent: any, args: any, context: any) => Promise<import("@webresto/core/models/Order").default>;
64
+ };
65
+ orderSetDishAmount: {
66
+ def: string;
67
+ fn: (parent: any, args: any, context: any) => Promise<import("@webresto/core/models/Order").default>;
68
+ };
69
+ orderSetDishComment: {
70
+ def: string;
71
+ fn: (parent: any, args: any, context: any) => Promise<import("@webresto/core/models/Order").default>;
72
+ };
73
+ orderUpdate: {
74
+ def: string;
75
+ fn: (parent: any, args: any, context: any) => Promise<{
76
+ id: string;
77
+ shortId: string;
78
+ dishes: number[] | import("@webresto/core/models/OrderDish").default[];
79
+ discount: any;
80
+ paymentMethod: any;
81
+ paymentMethodTitle: string;
82
+ paid: {
83
+ type: string;
84
+ defaultsTo: boolean;
85
+ };
86
+ isPaymentPromise: boolean;
87
+ dishesCount: number;
88
+ uniqueDishes: number;
89
+ modifiers: any;
90
+ customer: any;
91
+ address: any;
92
+ comment: string;
93
+ personsCount: string;
94
+ date: string;
95
+ problem: boolean;
96
+ rmsDelivered: boolean;
97
+ rmsId: string;
98
+ rmsOrderNumber: string;
99
+ rmsOrderData: any;
100
+ rmsDeliveryDate: string;
101
+ rmsErrorMessage: string;
102
+ rmsErrorCode: string;
103
+ rmsStatusCode: string;
104
+ deliveryStatus: string;
105
+ selfService: boolean;
106
+ deliveryDescription: string;
107
+ message: string;
108
+ deliveryItem: any;
109
+ deliveryCost: number;
110
+ totalWeight: number;
111
+ total: number;
112
+ trifleFrom: number;
113
+ orderTotal: number;
114
+ discountTotal: number;
115
+ orderDate: string;
116
+ customData: any;
117
+ state: string;
118
+ toJSON(): any;
119
+ }>;
120
+ };
121
+ };
122
+ };
123
+ export default _default;
@@ -0,0 +1,176 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const checkExpression_1 = require("@webresto/core/libs/checkExpression");
4
+ const getEmitter_1 = require("@webresto/core/libs/getEmitter");
5
+ const errorWrapper_1 = require("../../lib/errorWrapper");
6
+ exports.default = {
7
+ Query: {
8
+ order: {
9
+ def: '""" если orderId не задан, вернется новая корзина """ order(orderId: String, shortId: String, orderNumber: String): Order',
10
+ fn: async function (parent, args, context) {
11
+ let order;
12
+ let criteria = {};
13
+ if (args.orderNumber) {
14
+ criteria["rmsOrderNumber"] = args.orderNumber;
15
+ criteria["sort"] = "createdAt DESC";
16
+ }
17
+ else if (args.orderId) {
18
+ criteria["id"] = args.orderId;
19
+ }
20
+ else if (args.shortId) {
21
+ criteria["shortId"] = args.shortId;
22
+ }
23
+ if (Object.keys(criteria).length !== 0) {
24
+ order = (await Order.find(criteria))[0];
25
+ }
26
+ if (!order) {
27
+ sails.log.error("GQL > order resolver error: ", `order with id ${args.orderId} . Trying make new cart.`);
28
+ order = await getNewCart(args.orderId);
29
+ }
30
+ return await Order.populate(order.id);
31
+ },
32
+ },
33
+ },
34
+ Mutation: {
35
+ orderAddDish: {
36
+ def: "orderAddDish(orderId: String, dishId: String, amount: Int, modifiers: Json, comment: String, from: String, replace: Boolean, orderDishId: Int): Order",
37
+ fn: async function (parent, args, context) {
38
+ let order;
39
+ if (args.modifiers) {
40
+ args.modifiers.forEach((modifier) => {
41
+ if (modifier.amount === undefined || modifier.id === undefined)
42
+ throw new errorWrapper_1.Error(0, "ERROR", `modifier required (amount, id) for dish: ${args.dishId} current values: id: ${modifier.id}, amount: ${modifier.amount}`);
43
+ });
44
+ }
45
+ if (args.orderId)
46
+ order = await Order.findOne({ id: args.orderId });
47
+ if (!order) {
48
+ sails.log.error("GQL > orderAddDish resolver error: ", `order with id ${args.orderId} has problem. Trying make new cart.`);
49
+ order = await getNewCart(args.orderId);
50
+ }
51
+ const dish = await Dish.findOne({ id: args.dishId });
52
+ if (!dish && !args.replace)
53
+ throw new errorWrapper_1.Error(0, "ERROR", `dish with id ${args.dishId} not found`);
54
+ if (dish && checkExpression_1.default(dish) === "promo") {
55
+ let additionalInfo;
56
+ try {
57
+ additionalInfo = JSON.parse(dish.additionalInfo);
58
+ }
59
+ catch (e) { }
60
+ if (additionalInfo && additionalInfo.defaultOrderDish) {
61
+ // Исключение на товар в каждую корзину
62
+ }
63
+ else {
64
+ throw new errorWrapper_1.Error(0, "ERROR", `"${dish.name}" является акционным и не может быть добавлено пользователем`);
65
+ }
66
+ }
67
+ await Order.addDish(order.id, args.dishId, args.amount, args.modifiers || [], args.comment, args.from, args.replace, args.orderDishId);
68
+ return await Order.countCart(order);
69
+ },
70
+ },
71
+ orderReplaceDish: {
72
+ def: "orderReplaceDish(orderId: String!, orderDishId: Int!, amount: Int, modifiers: Json, comment: String, from: String): Order",
73
+ fn: async (parent, args, context) => {
74
+ let order;
75
+ if (args.orderId)
76
+ order = await Order.findOne({ id: args.orderId });
77
+ if (!order) {
78
+ sails.log.error("GQL > orderReplaceDish resolver error: ", `order with id ${args.orderId} has problem. Trying make new cart.`);
79
+ order = await getNewCart(args.orderId);
80
+ }
81
+ if (order.paid || order.state === "ORDER") {
82
+ order = await getNewCart();
83
+ }
84
+ await Order.addDish(order.id, args.dishId, args.amount, args.modifiers || [], args.comment, args.from, args.replace, args.orderDishId);
85
+ return await Order.countCart(order);
86
+ },
87
+ },
88
+ orderRemoveDish: {
89
+ def: "orderRemoveDish(id: String!, orderDishId: Int!, amount: Int): Order",
90
+ fn: async function (parent, args, context) {
91
+ let order;
92
+ order = await Order.findOne({ id: args.id });
93
+ if (!order) {
94
+ sails.log.error("GQL > orderRemoveDish resolver error: ", `order with id ${args.orderId} has problem. Trying make new cart.`);
95
+ order = await getNewCart(args.orderId);
96
+ }
97
+ if (order.paid || order.state === "ORDER") {
98
+ order = await getNewCart();
99
+ }
100
+ const orderDish = await OrderDish.findOne({ id: args.orderDishId });
101
+ await Order.removeDish(order.id, orderDish, args.amount, false);
102
+ return await Order.countCart(order);
103
+ },
104
+ },
105
+ orderSetDishAmount: {
106
+ def: "orderSetDishAmount(id: String, orderDishId: Int, amount: Int): Order",
107
+ fn: async function (parent, args, context) {
108
+ let order;
109
+ order = await Order.findOne(args.id);
110
+ if (!order) {
111
+ sails.log.error("GQL > orderSetDishAmount resolver error: ", `order with id ${args.orderId} has problem. Trying make new cart.`);
112
+ order = await getNewCart(args.orderId);
113
+ }
114
+ if (order.paid || order.state === "ORDER") {
115
+ order = await getNewCart();
116
+ }
117
+ let dish = await OrderDish.findOne(args.orderDishId).populate("dish");
118
+ if (!dish)
119
+ throw new errorWrapper_1.Error(0, "ERROR", `OrderDish with id ${args.orderDishId} not found`);
120
+ if (!dish.dish)
121
+ throw new errorWrapper_1.Error(0, "ERROR", `Dish in OrderDish with id ${args.orderDishId} not found`);
122
+ await Order.setCount(order.id, dish, args.amount);
123
+ return await Order.countCart(order);
124
+ },
125
+ },
126
+ orderSetDishComment: {
127
+ def: "orderSetDishComment(id: String, orderDishId: Int, comment: String): Order",
128
+ fn: async function (parent, args, context) {
129
+ let order;
130
+ const data = args;
131
+ const orderId = data.orderId;
132
+ const comment = data.comment || "";
133
+ const dishId = data.dishId;
134
+ if (!dishId) {
135
+ throw new errorWrapper_1.Error(0, "ERROR", "dishId is required");
136
+ }
137
+ order = await Order.findOne(orderId);
138
+ if (!order) {
139
+ sails.log.error("GQL > orderSetDishComment resolver error: ", `order with id ${args.orderId} has problem. Trying make new cart.`);
140
+ order = await getNewCart(args.orderId);
141
+ }
142
+ if (order.paid || order.state === "ORDER") {
143
+ order = await getNewCart();
144
+ }
145
+ const dish = await OrderDish.findOne({ id: dishId }).populate("dish");
146
+ if (!dish) {
147
+ throw new errorWrapper_1.Error(0, "ERROR", `Dish with id ${dishId} not found`);
148
+ }
149
+ await order.setComment(dish, comment);
150
+ return await Order.countCart(order);
151
+ },
152
+ },
153
+ orderUpdate: {
154
+ def: '"""Experimental! allowed only for trifleFrom """ orderUpdate(order: Json): Order',
155
+ fn: async function (parent, args, context) {
156
+ let order = args.order;
157
+ if (!order.id)
158
+ throw "order.id field is required";
159
+ await Order.update({ id: order.id }, { trifleFrom: order.trifleFrom });
160
+ return await Order.populate(order.id);
161
+ },
162
+ },
163
+ },
164
+ };
165
+ // Generate new cart
166
+ async function getNewCart(orderId) {
167
+ let order;
168
+ let initOrder = {};
169
+ // Pass oredrId from frontend
170
+ if (orderId)
171
+ initOrder["id"] = orderId;
172
+ getEmitter_1.default().emit("http-api:init-newcart", initOrder);
173
+ order = await Order.create(initOrder).fetch();
174
+ await getEmitter_1.default().emit("http-api:create-newcart", order);
175
+ return order;
176
+ }