mandarina-server 2.1.11 → 2.1.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,7 +2,7 @@ import { Prisma } from "prisma-binding";
2
2
  import { ContextParameters } from "graphql-yoga/dist/types";
3
3
  import { ActionType } from "mandarina/build/Auth/Auth";
4
4
  import { Schema } from "mandarina";
5
- import { ErrorFromServerMapper } from "mandarina/src/Schema/Schema";
5
+ import { ErrorFromServerMapper } from "mandarina/build/Schema/Schema";
6
6
  import { UserType } from "../Mandarina";
7
7
  import { GraphQLResolveInfo } from "graphql";
8
8
  /**
@@ -28,7 +28,7 @@ export declare class Table {
28
28
  getDefaultActions(type: operationType): {
29
29
  [resolverName: string]: (_: any, args: any, context: Context, info: any) => void;
30
30
  };
31
- insertWhereIntoInfo: (info: GraphQLResolveInfo, user: UserType | null | undefined, isSingleMutation: boolean | undefined, action: "read" | "create" | "update" | "delete", operationName: string) => {
31
+ insertWhereIntoInfo: (info: GraphQLResolveInfo, user: UserType | null | undefined, isSingleMutation: boolean | undefined, action: ActionType, operationName: string) => {
32
32
  fields: string[];
33
33
  queryString: string;
34
34
  };
File without changes
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mandarina-server",
3
- "version": "2.1.11",
3
+ "version": "2.1.13",
4
4
  "description": "Mandarina for server side",
5
5
  "main": "build/index.js",
6
6
  "types": "build/index.d.ts",
@@ -16,15 +16,15 @@
16
16
  "@types/ws": "^6.0.1",
17
17
  "@types/graphql-fields": "^1.3.0",
18
18
  "graphql-fields": "2.0.3",
19
- "yaml": "^1.6.0",
20
- "typescript": "3.8.3"
19
+ "yaml": "^1.6.0"
21
20
  },
22
21
  "peerDependencies": {
22
+ "typescript": "3.8.3",
23
23
  "lodash": ">=4.17.21",
24
24
  "@types/lodash": ">=4.14.192",
25
25
  "@types/node": ">=12.0.10",
26
26
  "graphql-yoga": ">=1.17.4",
27
- "mandarina": "2.1.10",
27
+ "mandarina": "2.1.12",
28
28
  "prisma-binding": ">=2.3.15"
29
29
  },
30
30
  "devDependencies": {
@@ -32,7 +32,7 @@
32
32
  "graphql-yoga": "^1.18.0",
33
33
  "jest": "^24.8.0",
34
34
  "ts-jest": "22.4.6",
35
- "mandarina": "2.1.10",
35
+ "mandarina": "2.1.12",
36
36
  "prisma-binding": "^2.3.15"
37
37
  },
38
38
  "jest": {
@@ -8,22 +8,46 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
8
8
  step((generator = generator.apply(thisArg, _arguments || [])).next());
9
9
  });
10
10
  };
11
- var __importDefault = (this && this.__importDefault) || function (mod) {
12
- return (mod && mod.__esModule) ? mod : { "default": mod };
11
+ var __generator = (this && this.__generator) || function (thisArg, body) {
12
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
13
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
+ function verb(n) { return function (v) { return step([n, v]); }; }
15
+ function step(op) {
16
+ if (f) throw new TypeError("Generator is already executing.");
17
+ while (_) try {
18
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
19
+ if (y = 0, t) op = [op[0] & 2, t.value];
20
+ switch (op[0]) {
21
+ case 0: case 1: t = op; break;
22
+ case 4: _.label++; return { value: op[1], done: false };
23
+ case 5: _.label++; y = op[1]; op = [0]; continue;
24
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
25
+ default:
26
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
27
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
28
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
29
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
30
+ if (t[2]) _.ops.pop();
31
+ _.trys.pop(); continue;
32
+ }
33
+ op = body.call(thisArg, _);
34
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
35
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
+ }
13
37
  };
14
38
  Object.defineProperty(exports, "__esModule", { value: true });
15
- const Schema_1 = require("mandarina/build/Schema/Schema");
16
- const TableInstanceNotFound_1 = require("../Errors/TableInstanceNotFound");
17
- const UniqueActionError_1 = require("../Errors/UniqueActionError");
18
- const Mandarina_1 = __importDefault(require("../Mandarina"));
19
- class CustomAction {
39
+ var Schema_1 = require("mandarina/build/Schema/Schema");
40
+ var TableInstanceNotFound_1 = require("../Errors/TableInstanceNotFound");
41
+ var UniqueActionError_1 = require("../Errors/UniqueActionError");
42
+ var Mandarina_1 = require("../Mandarina");
43
+ var CustomAction = /** @class */ (function () {
20
44
  /**
21
45
  *
22
46
  *
23
47
  * @param schema
24
48
  * @param actionOptions
25
49
  */
26
- constructor(schema, actionOptions) {
50
+ function CustomAction(schema, actionOptions) {
27
51
  CustomAction.instances = CustomAction.instances || {};
28
52
  if (schema instanceof Schema_1.Schema) {
29
53
  this.schema = schema;
@@ -38,48 +62,60 @@ class CustomAction {
38
62
  this.actions = actionOptions.actions;
39
63
  CustomAction.instances[this.name] = this;
40
64
  }
41
- static getInstance(name) {
65
+ CustomAction.getInstance = function (name) {
42
66
  if (!CustomAction.instances[name]) {
43
67
  throw new TableInstanceNotFound_1.TableInstanceNotFound(name);
44
68
  }
45
69
  return CustomAction.instances[name];
46
- }
47
- getFields() {
70
+ };
71
+ CustomAction.prototype.getFields = function () {
48
72
  return this.schema && this.schema.getFields();
49
- }
50
- getActions() {
51
- const actions = this.actions || {};
52
- let result = {};
53
- Object.keys(actions).forEach((action) => {
54
- result[action] = (_, args, context, info) => __awaiter(this, void 0, void 0, function* () {
55
- const user = yield Mandarina_1.default.config.getUser(context);
56
- const roles = (user && user.roles) || [];
57
- const permissions = actions[action].permission || [];
58
- if (permissions.includes('nobody')) {
59
- throw new Error('Action not allowed');
60
- }
61
- if (permissions.includes('everybody') || permissions.some(permission => roles.includes(permission))) {
62
- console.log('***************', `Action "${action}" not allowed for this user`, '***************');
63
- console.warn(user && user.id, action);
64
- console.warn(user && user.roles, permissions);
65
- console.log('*****************************************************************************');
66
- //throw new Error(`Action "${action}" not allowed for this user`)
67
- }
68
- const result = yield actions[action].action(_, args, context, info);
69
- context.result = result;
70
- if (CustomAction.hook) {
71
- context.schemaName = this.name;
72
- context.name = action;
73
- yield CustomAction.hook(_, args, context, info);
74
- }
75
- return result;
76
- });
73
+ };
74
+ CustomAction.prototype.getActions = function () {
75
+ var _this = this;
76
+ var actions = this.actions || {};
77
+ var result = {};
78
+ Object.keys(actions).forEach(function (action) {
79
+ result[action] = function (_, args, context, info) { return __awaiter(_this, void 0, void 0, function () {
80
+ var user, roles, permissions, result;
81
+ return __generator(this, function (_a) {
82
+ switch (_a.label) {
83
+ case 0: return [4 /*yield*/, Mandarina_1.default.config.getUser(context)];
84
+ case 1:
85
+ user = _a.sent();
86
+ roles = (user && user.roles) || [];
87
+ permissions = actions[action].permission || [];
88
+ if (permissions.includes('nobody')) {
89
+ throw new Error('Action not allowed');
90
+ }
91
+ if (permissions.includes('everybody') || permissions.some(function (permission) { return roles.includes(permission); })) {
92
+ console.log('***************', "Action \"" + action + "\" not allowed for this user", '***************');
93
+ console.warn(user && user.id, action);
94
+ console.warn(user && user.roles, permissions);
95
+ console.log('*****************************************************************************');
96
+ //throw new Error(`Action "${action}" not allowed for this user`)
97
+ }
98
+ return [4 /*yield*/, actions[action].action(_, args, context, info)];
99
+ case 2:
100
+ result = _a.sent();
101
+ context.result = result;
102
+ if (!CustomAction.hook) return [3 /*break*/, 4];
103
+ context.schemaName = this.name;
104
+ context.name = action;
105
+ return [4 /*yield*/, CustomAction.hook(_, args, context, info)];
106
+ case 3:
107
+ _a.sent();
108
+ _a.label = 4;
109
+ case 4: return [2 /*return*/, result];
110
+ }
111
+ });
112
+ }); };
77
113
  });
78
114
  return result;
79
- }
80
- }
115
+ };
116
+ CustomAction.setGlobalHook = function (hook) {
117
+ CustomAction.hook = hook;
118
+ };
119
+ return CustomAction;
120
+ }());
81
121
  exports.CustomAction = CustomAction;
82
- CustomAction.setGlobalHook = (hook) => {
83
- CustomAction.hook = hook;
84
- };
85
- //# sourceMappingURL=CustomAction.js.map
@@ -1,13 +1,24 @@
1
1
  "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
2
+ var __extends = (this && this.__extends) || (function () {
3
+ var extendStatics = function (d, b) {
4
+ extendStatics = Object.setPrototypeOf ||
5
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
6
+ function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
7
+ return extendStatics(d, b);
8
+ };
9
+ return function (d, b) {
10
+ extendStatics(d, b);
11
+ function __() { this.constructor = d; }
12
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
13
+ };
14
+ })();
5
15
  Object.defineProperty(exports, "__esModule", { value: true });
6
- const BaseError_1 = __importDefault(require("mandarina/build/Errors/BaseError"));
7
- class TableInstanceNotFound extends BaseError_1.default {
8
- constructor(schemaName) {
9
- super(`The table ${schemaName} was not instantiated`);
16
+ var BaseError_1 = require("mandarina/build/Errors/BaseError");
17
+ var TableInstanceNotFound = /** @class */ (function (_super) {
18
+ __extends(TableInstanceNotFound, _super);
19
+ function TableInstanceNotFound(schemaName) {
20
+ return _super.call(this, "The table " + schemaName + " was not instantiated") || this;
10
21
  }
11
- }
22
+ return TableInstanceNotFound;
23
+ }(BaseError_1.default));
12
24
  exports.TableInstanceNotFound = TableInstanceNotFound;
13
- //# sourceMappingURL=TableInstanceNotFound.js.map
@@ -1,14 +1,27 @@
1
1
  "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
2
+ var __extends = (this && this.__extends) || (function () {
3
+ var extendStatics = function (d, b) {
4
+ extendStatics = Object.setPrototypeOf ||
5
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
6
+ function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
7
+ return extendStatics(d, b);
8
+ };
9
+ return function (d, b) {
10
+ extendStatics(d, b);
11
+ function __() { this.constructor = d; }
12
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
13
+ };
14
+ })();
5
15
  Object.defineProperty(exports, "__esModule", { value: true });
6
- const BaseError_1 = __importDefault(require("mandarina/build/Errors/BaseError"));
7
- class UniqueActionError extends BaseError_1.default {
8
- constructor(schemaName) {
9
- const name = typeof schemaName === "string" ? schemaName : schemaName.name;
10
- super(`The action "${name}" already exists, action name should be unique.`);
16
+ var BaseError_1 = require("mandarina/build/Errors/BaseError");
17
+ var UniqueActionError = /** @class */ (function (_super) {
18
+ __extends(UniqueActionError, _super);
19
+ function UniqueActionError(schemaName) {
20
+ var _this = this;
21
+ var name = typeof schemaName === "string" ? schemaName : schemaName.name;
22
+ _this = _super.call(this, "The action \"" + name + "\" already exists, action name should be unique.") || this;
23
+ return _this;
11
24
  }
12
- }
25
+ return UniqueActionError;
26
+ }(BaseError_1.default));
13
27
  exports.UniqueActionError = UniqueActionError;
14
- //# sourceMappingURL=UniqueActionError.js.map
package/src/Mandarina.js CHANGED
@@ -1,41 +1,57 @@
1
1
  "use strict";
2
+ var __assign = (this && this.__assign) || function () {
3
+ __assign = Object.assign || function(t) {
4
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
5
+ s = arguments[i];
6
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
+ t[p] = s[p];
8
+ }
9
+ return t;
10
+ };
11
+ return __assign.apply(this, arguments);
12
+ };
2
13
  Object.defineProperty(exports, "__esModule", { value: true });
3
- const Table_1 = require("./Table/Table");
4
- const CustomAction_1 = require("./Action/CustomAction");
5
- const utils_1 = require("./cli/utils");
6
- class Mandarina {
7
- static load() {
8
- const config = utils_1.getConfig();
9
- utils_1.loadSchemas(config.dir);
14
+ var Table_1 = require("./Table/Table");
15
+ var CustomAction_1 = require("./Action/CustomAction");
16
+ var utils_1 = require("./cli/utils");
17
+ var Mandarina = /** @class */ (function () {
18
+ function Mandarina() {
10
19
  }
11
- static getQuery() {
12
- let Query = {};
13
- for (const tableName in Table_1.Table.instances) {
14
- const table = Table_1.Table.getInstance(tableName);
15
- Query = Object.assign(Object.assign({}, Query), table.getDefaultActions('query'));
20
+ Mandarina.load = function () {
21
+ var config = utils_1.getConfig();
22
+ utils_1.loadSchemas(config.dir);
23
+ };
24
+ Mandarina.getQuery = function () {
25
+ var Query = {};
26
+ for (var tableName in Table_1.Table.instances) {
27
+ var table = Table_1.Table.getInstance(tableName);
28
+ Query = __assign(__assign({}, Query), table.getDefaultActions('query'));
16
29
  }
17
30
  return Query;
18
- }
19
- static getMutation() {
20
- let Mutation = {};
21
- for (const tableName in Table_1.Table.instances) {
22
- const table = Table_1.Table.getInstance(tableName);
23
- Mutation = Object.assign(Object.assign({}, Mutation), table.getDefaultActions('mutation'));
31
+ };
32
+ Mandarina.getMutation = function () {
33
+ var Mutation = {};
34
+ for (var tableName in Table_1.Table.instances) {
35
+ var table = Table_1.Table.getInstance(tableName);
36
+ Mutation = __assign(__assign({}, Mutation), table.getDefaultActions('mutation'));
24
37
  }
25
- for (const actionName in CustomAction_1.CustomAction.instances) {
26
- const action = CustomAction_1.CustomAction.getInstance(actionName);
27
- Mutation = Object.assign(Object.assign({}, Mutation), action.getActions());
38
+ for (var actionName in CustomAction_1.CustomAction.instances) {
39
+ var action = CustomAction_1.CustomAction.getInstance(actionName);
40
+ Mutation = __assign(__assign({}, Mutation), action.getActions());
28
41
  }
29
42
  return Mutation;
30
- }
31
- }
43
+ };
44
+ Mandarina.config = {
45
+ getUser: function (_a) {
46
+ var user = _a.user;
47
+ return user;
48
+ },
49
+ };
50
+ Mandarina.configure = function (options) {
51
+ if (options.getUser) {
52
+ Mandarina.config.getUser = options.getUser;
53
+ }
54
+ };
55
+ return Mandarina;
56
+ }());
32
57
  exports.default = Mandarina;
33
- Mandarina.config = {
34
- getUser: ({ user }) => user,
35
- };
36
- Mandarina.configure = (options) => {
37
- if (options.getUser) {
38
- Mandarina.config.getUser = options.getUser;
39
- }
40
- };
41
- //# sourceMappingURL=Mandarina.js.map
@@ -1,4 +1,15 @@
1
1
  "use strict";
2
+ var __assign = (this && this.__assign) || function () {
3
+ __assign = Object.assign || function(t) {
4
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
5
+ s = arguments[i];
6
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
+ t[p] = s[p];
8
+ }
9
+ return t;
10
+ };
11
+ return __assign.apply(this, arguments);
12
+ };
2
13
  var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
14
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
15
  return new (P || (P = Promise))(function (resolve, reject) {
@@ -8,20 +19,44 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
8
19
  step((generator = generator.apply(thisArg, _arguments || [])).next());
9
20
  });
10
21
  };
11
- var __importDefault = (this && this.__importDefault) || function (mod) {
12
- return (mod && mod.__esModule) ? mod : { "default": mod };
22
+ var __generator = (this && this.__generator) || function (thisArg, body) {
23
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
24
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
25
+ function verb(n) { return function (v) { return step([n, v]); }; }
26
+ function step(op) {
27
+ if (f) throw new TypeError("Generator is already executing.");
28
+ while (_) try {
29
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
30
+ if (y = 0, t) op = [op[0] & 2, t.value];
31
+ switch (op[0]) {
32
+ case 0: case 1: t = op; break;
33
+ case 4: _.label++; return { value: op[1], done: false };
34
+ case 5: _.label++; y = op[1]; op = [0]; continue;
35
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
36
+ default:
37
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
38
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
39
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
40
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
41
+ if (t[2]) _.ops.pop();
42
+ _.trys.pop(); continue;
43
+ }
44
+ op = body.call(thisArg, _);
45
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
46
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
47
+ }
13
48
  };
14
49
  Object.defineProperty(exports, "__esModule", { value: true });
15
- const mandarina_1 = require("mandarina");
16
- const UniqueSchemaError_1 = require("mandarina/build/Errors/UniqueSchemaError");
17
- const SchemaInstanceNotFound_1 = require("mandarina/build/Errors/SchemaInstanceNotFound");
18
- const utils_1 = require("mandarina/build/Schema/utils");
19
- const MissingIDTableError_1 = require("mandarina/build/Errors/MissingIDTableError");
20
- const Mandarina_1 = __importDefault(require("../Mandarina"));
21
- const Mutate_1 = require("mandarina/build/Operations/Mutate");
22
- const language_1 = require("graphql/language");
23
- const stringify_object_1 = __importDefault(require("stringify-object"));
24
- const lodash_1 = require("lodash");
50
+ var mandarina_1 = require("mandarina");
51
+ var UniqueSchemaError_1 = require("mandarina/build/Errors/UniqueSchemaError");
52
+ var SchemaInstanceNotFound_1 = require("mandarina/build/Errors/SchemaInstanceNotFound");
53
+ var utils_1 = require("mandarina/build/Schema/utils");
54
+ var MissingIDTableError_1 = require("mandarina/build/Errors/MissingIDTableError");
55
+ var Mandarina_1 = require("../Mandarina");
56
+ var Mutate_1 = require("mandarina/build/Operations/Mutate");
57
+ var language_1 = require("graphql/language");
58
+ var stringify_object_1 = require("stringify-object");
59
+ var lodash_1 = require("lodash");
25
60
  // import {flatten, unflatten} from "flat";
26
61
  /**
27
62
  *
@@ -30,16 +65,21 @@ const lodash_1 = require("lodash");
30
65
  * Form
31
66
  * List of results
32
67
  */
33
- class Table {
34
- constructor(schema, tableOptions) {
35
- this.insertWhereIntoInfo = (info, user, isSingleMutation = false, action, operationName) => {
68
+ var Table = /** @class */ (function () {
69
+ function Table(schema, tableOptions) {
70
+ var _this = this;
71
+ this.insertWhereIntoInfo = function (info, user, isSingleMutation, action, operationName) {
72
+ if (isSingleMutation === void 0) { isSingleMutation = false; }
36
73
  var _a, _b;
37
- const field = [];
38
- const fields = new Set();
39
- let required = false;
40
- const allowedVariables = ((_b = (_a = info.fieldNodes[0]) === null || _a === void 0 ? void 0 : _a.arguments) === null || _b === void 0 ? void 0 : _b.map(({ name: { value } }) => value)) || [];
41
- const query = language_1.visit(info.operation, {
42
- enter: (node, key, parent, path, ancestors) => {
74
+ var field = [];
75
+ var fields = new Set();
76
+ var required = false;
77
+ var allowedVariables = ((_b = (_a = info.fieldNodes[0]) === null || _a === void 0 ? void 0 : _a.arguments) === null || _b === void 0 ? void 0 : _b.map(function (_a) {
78
+ var value = _a.name.value;
79
+ return value;
80
+ })) || [];
81
+ var query = language_1.visit(info.operation, {
82
+ enter: function (node, key, parent, path, ancestors) {
43
83
  if (node.kind === 'VariableDefinition') {
44
84
  if (!allowedVariables.includes(node === null || node === void 0 ? void 0 : node.variable.name.value)) {
45
85
  return null;
@@ -50,31 +90,31 @@ class Table {
50
90
  }
51
91
  if (node.kind === 'Field' && node.name.value !== '__typename') {
52
92
  field.push(node.name.value);
53
- const internalField = field.slice(1).join('.');
54
- let table;
93
+ var internalField = field.slice(1).join('.');
94
+ var table = void 0;
55
95
  if (internalField) {
56
96
  fields.add(internalField);
57
- const def = this.schema.getPathDefinition(internalField);
97
+ var def = _this.schema.getPathDefinition(internalField);
58
98
  if (def.isTable && def.isArray) {
59
99
  table = Table.instances[def.type];
60
100
  }
61
101
  }
62
102
  else {
63
- table = this;
103
+ table = _this;
64
104
  }
65
- if (table && table.options.where && (!isSingleMutation && table === this)) {
66
- const where = table.options.where(user, action, operationName);
105
+ if (table && table.options.where && (!isSingleMutation && table === _this)) {
106
+ var where = table.options.where(user, action, operationName);
67
107
  if (!where || lodash_1.isEmpty(where))
68
108
  return;
69
- const clone = Mutate_1.deepClone(node);
70
- const originalWhereObj = clone.arguments ? clone.arguments.find((a) => a.name.value === 'where') : null;
71
- let originalWhereString = '';
72
- if (originalWhereObj && table === this) {
109
+ var clone = Mutate_1.deepClone(node);
110
+ var originalWhereObj = clone.arguments ? clone.arguments.find(function (a) { return a.name.value === 'where'; }) : null;
111
+ var originalWhereString = '';
112
+ if (originalWhereObj && table === _this) {
73
113
  originalWhereString = language_1.print(originalWhereObj.value);
74
114
  required = true;
75
115
  }
76
- const newWhereString = stringify_object_1.default(where, { singleQuotes: false });
77
- let finalWhereString = originalWhereString ? `{AND:[${originalWhereString},${newWhereString}]}` : newWhereString;
116
+ var newWhereString = stringify_object_1.default(where, { singleQuotes: false });
117
+ var finalWhereString = originalWhereString ? "{AND:[" + originalWhereString + "," + newWhereString + "]}" : newWhereString;
78
118
  if (originalWhereObj) {
79
119
  originalWhereObj.value = language_1.parseValue(new language_1.Source(finalWhereString));
80
120
  }
@@ -90,17 +130,17 @@ class Table {
90
130
  }
91
131
  return;
92
132
  },
93
- leave(node) {
133
+ leave: function (node) {
94
134
  if (node.kind === 'Field' && node.name.value !== '__typename') {
95
135
  field.pop();
96
136
  }
97
137
  }
98
138
  });
99
- let queryString = language_1.print(query);
139
+ var queryString = language_1.print(query);
100
140
  if (required) {
101
141
  queryString = queryString.replace(/\$where: (\w*)Input(,| |\))/, '$where: $1Input!$2');
102
142
  }
103
- return { fields: Array.from(fields), queryString };
143
+ return { fields: Array.from(fields), queryString: queryString };
104
144
  };
105
145
  Table.instances = Table.instances || {};
106
146
  this.schema = schema;
@@ -111,18 +151,18 @@ class Table {
111
151
  if (Table.instances[this.name]) {
112
152
  throw new UniqueSchemaError_1.UniqueSchemaError(this.name);
113
153
  }
114
- this.options = Object.assign({}, tableOptions);
154
+ this.options = __assign({}, tableOptions);
115
155
  Table.instances[this.name] = this;
116
156
  }
117
- static getInstance(name) {
157
+ Table.getInstance = function (name) {
118
158
  if (!Table.instances[name]) {
119
159
  throw new SchemaInstanceNotFound_1.SchemaInstanceNotFound(name);
120
160
  }
121
161
  return Table.instances[name];
122
- }
123
- getFields() {
162
+ };
163
+ Table.prototype.getFields = function () {
124
164
  return this.schema.getFields();
125
- }
165
+ };
126
166
  /*
127
167
  * It apply the fields permissions policy by action and roles, throw an exception if is not a valid request
128
168
  *
@@ -142,112 +182,114 @@ class Table {
142
182
  }
143
183
  }
144
184
  */
145
- shouldHasManyUpdate() {
146
- const fields = this.schema.getFields().filter(f => f !== 'createdAt' && f !== 'createdAt');
185
+ Table.prototype.shouldHasManyUpdate = function () {
186
+ var fields = this.schema.getFields().filter(function (f) { return f !== 'createdAt' && f !== 'createdAt'; });
147
187
  return fields.length > 0;
148
- }
188
+ };
149
189
  //Insert where option in to the query
150
190
  // static dotConcat = (a: string | undefined, b: string) => a ? `${a}.${b}` : b;
151
- getDefaultActions(type) {
191
+ Table.prototype.getDefaultActions = function (type) {
192
+ var _this = this;
152
193
  // OperationName for query is user or users, for mutation are createUser, updateUser ....
153
- const operationNames = Object.values(this.schema.names[type]);
154
- const resultResolvers = {};
155
- operationNames.forEach((operationName) => {
156
- if (!this.shouldHasManyUpdate())
194
+ var operationNames = Object.values(this.schema.names[type]);
195
+ var resultResolvers = {};
196
+ operationNames.forEach(function (operationName) {
197
+ if (!_this.shouldHasManyUpdate())
157
198
  return;
158
- resultResolvers[operationName] = (_, args = {}, context, info) => __awaiter(this, void 0, void 0, function* () {
159
- context.originalArgs = args;
160
- const user = yield Mandarina_1.default.config.getUser(context);
161
- const subOperationName = operationName.substr(0, 6);
162
- const action = (['create', 'update', 'delete'].includes(subOperationName) ? subOperationName : 'read');
163
- context.action = action;
164
- let result;
165
- const capitalizedAction = utils_1.capitalize(action);
166
- context.operationName = operationName;
167
- yield this.callHook(this.name, 'beforeValidate', _, args, context, info);
168
- const isSingleMutation = operationName === this.schema.names.mutation.update || operationName === this.schema.names.mutation.create;
169
- let { queryString, fields } = this.insertWhereIntoInfo(info, user, isSingleMutation, action, operationName);
170
- if (type === 'mutation') {
171
- // if (errors.length > 0) {
172
- // await this.callHook('validationFailed', action, _, args, context, info);
173
- // } else {
174
- // await this.callHook('afterValidate', action, _, args, context, info);
175
- // }
176
- if (isSingleMutation && (action === 'update' || action === 'delete')) {
177
- const where = this.options.where && this.options.where(user, action, operationName);
178
- if (where) {
179
- let finalWhere = args.where ? { AND: [args.where, where] } : where;
180
- const exists = (yield context.prisma.exists[this.name](finalWhere));
181
- if (!exists) {
182
- throw new Error(`${action} on ${this.schema.name} not found for ${JSON.stringify(where)}`);
183
- }
199
+ resultResolvers[operationName] = function (_, args, context, info) {
200
+ if (args === void 0) { args = {}; }
201
+ return __awaiter(_this, void 0, void 0, function () {
202
+ var user, subOperationName, action, result, capitalizedAction, isSingleMutation, _a, queryString, fields, where, finalWhere, exists, data, data;
203
+ return __generator(this, function (_b) {
204
+ switch (_b.label) {
205
+ case 0:
206
+ context.originalArgs = args;
207
+ return [4 /*yield*/, Mandarina_1.default.config.getUser(context)];
208
+ case 1:
209
+ user = _b.sent();
210
+ subOperationName = operationName.substr(0, 6);
211
+ action = (['create', 'update', 'delete'].includes(subOperationName) ? subOperationName : 'read');
212
+ context.action = action;
213
+ capitalizedAction = utils_1.capitalize(action);
214
+ context.operationName = operationName;
215
+ return [4 /*yield*/, this.callHook(this.name, 'beforeValidate', _, args, context, info)];
216
+ case 2:
217
+ _b.sent();
218
+ isSingleMutation = operationName === this.schema.names.mutation.update || operationName === this.schema.names.mutation.create;
219
+ _a = this.insertWhereIntoInfo(info, user, isSingleMutation, action, operationName), queryString = _a.queryString, fields = _a.fields;
220
+ if (!(type === 'mutation')) return [3 /*break*/, 8];
221
+ if (!(isSingleMutation && (action === 'update' || action === 'delete'))) return [3 /*break*/, 4];
222
+ where = this.options.where && this.options.where(user, action, operationName);
223
+ if (!where) return [3 /*break*/, 4];
224
+ finalWhere = args.where ? { AND: [args.where, where] } : where;
225
+ return [4 /*yield*/, context.prisma.exists[this.name](finalWhere)];
226
+ case 3:
227
+ exists = (_b.sent());
228
+ if (!exists) {
229
+ throw new Error(action + " on " + this.schema.name + " not found for " + JSON.stringify(where));
230
+ }
231
+ _b.label = 4;
232
+ case 4:
233
+ //VALIDATE IF USER CAN MUTATE THOSE FIELDS
234
+ this.schema.validateMutation(action, Mutate_1.deepClone(args), user && user.roles || []);
235
+ return [4 /*yield*/, this.callHook(this.name, "before" + capitalizedAction, _, args, context, info)];
236
+ case 5:
237
+ _b.sent();
238
+ return [4 /*yield*/, context.prisma.request(queryString, args)];
239
+ case 6:
240
+ data = (_b.sent());
241
+ if (data.errors) {
242
+ console.error(data.errors);
243
+ }
244
+ result = Object.values(data.data)[0];
245
+ context.result = result;
246
+ return [4 /*yield*/, this.callHook(this.name, "after" + capitalizedAction, _, args, context, info)];
247
+ case 7:
248
+ _b.sent();
249
+ this.schema.validateQuery(fields, user && user.roles || []);
250
+ _b.label = 8;
251
+ case 8:
252
+ if (!(type === 'query')) return [3 /*break*/, 12];
253
+ // console.dir(JSON.parse(JSON.stringify(info)),{depth:1})
254
+ return [4 /*yield*/, this.callHook(this.name, 'beforeQuery', _, args, context, info)];
255
+ case 9:
256
+ // console.dir(JSON.parse(JSON.stringify(info)),{depth:1})
257
+ _b.sent();
258
+ if (!!info.fieldName.match(/Connection$/)) {
259
+ this.schema.validateConnection(user && user.roles || []);
260
+ }
261
+ else {
262
+ this.schema.validateQuery(fields, user && user.roles || []);
263
+ }
264
+ //Validate if the roles is able to read those fields
265
+ if (operationName === this.schema.names.query.single) {
266
+ queryString = queryString.replace(operationName, this.schema.names.query.plural);
267
+ queryString = queryString.replace(new RegExp(this.schema.names.input.where.single + "!?"), this.schema.names.input.where.plural + '!');
268
+ }
269
+ return [4 /*yield*/, context.prisma.request(queryString, args)];
270
+ case 10:
271
+ data = (_b.sent());
272
+ if (data.errors) {
273
+ console.error(data.errors);
274
+ }
275
+ result = Object.values(data.data)[0];
276
+ if (operationName === this.schema.names.query.single) {
277
+ result = data.data[this.schema.names.query.plural];
278
+ result = result && result.length === 1 ? result[0] : null;
279
+ }
280
+ context.result = result;
281
+ return [4 /*yield*/, this.callHook(this.name, 'afterQuery', _, args, context, info)];
282
+ case 11:
283
+ _b.sent();
284
+ _b.label = 12;
285
+ case 12: return [2 /*return*/, result];
184
286
  }
185
- }
186
- //VALIDATE IF USER CAN MUTATE THOSE FIELDS
187
- this.schema.validateMutation(action, Mutate_1.deepClone(args), user && user.roles || []);
188
- yield this.callHook(this.name, `before${capitalizedAction}`, _, args, context, info);
189
- /*
190
- HACK https://github.com/prisma/prisma/issues/4327
191
- */
192
- // if (`before${capitalizedAction}` === 'beforeUpdate' || `before${capitalizedAction}` === 'beforeCreate') {
193
- // const flat = flatten(args.data)
194
- // const where = args.where
195
- // let run = false
196
- // let withDeleteMany: any = {}
197
- // let withoutDeleteMany: any = {}
198
- // Object.keys(flat).forEach((key) => {
199
- // if (key.match(/\.deleteMany\.0$/)) {
200
- // run = true
201
- // withDeleteMany[key] = flat[key]
202
- // } else {
203
- // withoutDeleteMany[key] = flat[key]
204
- // }
205
- // })
206
- // if (run) {
207
- // await prismamethod({where, data: unflatten(withdeletemany)}, info);
208
- // args.data = unflatten(withoutDeleteMany)
209
- // }
210
- // }
211
- const data = (yield context.prisma.request(queryString, args));
212
- if (data.errors) {
213
- console.error(data.errors);
214
- }
215
- result = Object.values(data.data)[0];
216
- context.result = result;
217
- yield this.callHook(this.name, `after${capitalizedAction}`, _, args, context, info);
218
- this.schema.validateQuery(fields, user && user.roles || []);
219
- }
220
- if (type === 'query') {
221
- // console.dir(JSON.parse(JSON.stringify(info)),{depth:1})
222
- yield this.callHook(this.name, 'beforeQuery', _, args, context, info);
223
- if (!!info.fieldName.match(/Connection$/)) {
224
- this.schema.validateConnection(user && user.roles || []);
225
- }
226
- else {
227
- this.schema.validateQuery(fields, user && user.roles || []);
228
- }
229
- //Validate if the roles is able to read those fields
230
- if (operationName === this.schema.names.query.single) {
231
- queryString = queryString.replace(operationName, this.schema.names.query.plural);
232
- queryString = queryString.replace(new RegExp(`${this.schema.names.input.where.single}!?`), this.schema.names.input.where.plural + '!');
233
- }
234
- const data = (yield context.prisma.request(queryString, args));
235
- if (data.errors) {
236
- console.error(data.errors);
237
- }
238
- result = Object.values(data.data)[0];
239
- if (operationName === this.schema.names.query.single) {
240
- result = data.data[this.schema.names.query.plural];
241
- result = result && result.length === 1 ? result[0] : null;
242
- }
243
- context.result = result;
244
- yield this.callHook(this.name, 'afterQuery', _, args, context, info);
245
- }
246
- return result;
247
- });
287
+ });
288
+ });
289
+ };
248
290
  });
249
291
  return resultResolvers;
250
- }
292
+ };
251
293
  /**
252
294
  * Go back a mutation object to the original object
253
295
  */
@@ -261,80 +303,114 @@ class Table {
261
303
  * @param context
262
304
  * @param info
263
305
  */
264
- callHook(schemaName, name, _, args, context, info) {
265
- return __awaiter(this, void 0, void 0, function* () {
266
- try {
267
- let prefix = '';
268
- if (name.indexOf('before') === 0)
269
- prefix = 'before';
270
- if (name.indexOf('after') === 0)
271
- prefix = 'after';
272
- const globalHookHandler = Table.hooks[name];
273
- const hookHandler = this.options.hooks && this.options.hooks[name];
274
- if (args.data && prefix) {
275
- const fields = Object.keys(args.data);
276
- const schema = mandarina_1.Schema.getInstance(schemaName);
277
- for (const field of fields) {
278
- const def = schema.getPathDefinition(field);
279
- const inline = !!(def.table && def.table.relation && def.table.relation.link === 'INLINE');
280
- if (def.isTable) {
281
- const operations = Object.keys(args.data[field]);
282
- if (!Table.instances[def.type]) {
283
- //console.warn(`No table for ${def.type} no neasted hooks applied`)
284
- continue;
285
- }
286
- const table = Table.getInstance(def.type);
287
- for (const operation of operations) {
288
- const hookName = `${prefix}${utils_1.capitalize(operation)}`;
289
- const args2 = args.data[field][operation];
290
- if (Array.isArray(args2)) {
291
- for (const arg2 of args2) {
292
- if (inline) {
293
- yield table.callHook(def.type, hookName, _, arg2.data ? arg2 : { data: arg2 }, context, info);
294
- }
295
- else {
296
- yield table.callHook(def.type, hookName, _, arg2.data ? arg2 : { data: arg2 }, context, info);
297
- }
298
- }
299
- }
300
- else {
301
- if (inline) {
302
- yield table.callHook(def.type, hookName, _, args2.data ? args2 : { data: args2 }, context, info);
303
- }
304
- else {
305
- yield table.callHook(def.type, hookName, _, args2.data ? args2 : { data: args2 }, context, info);
306
- }
307
- }
308
- }
306
+ Table.prototype.callHook = function (schemaName, name, _, args, context, info) {
307
+ return __awaiter(this, void 0, void 0, function () {
308
+ var prefix, globalHookHandler, hookHandler, fields, schema, _i, fields_1, field, def, inline, operations, table, _a, operations_1, operation, hookName, args2, _b, args2_1, arg2, e_1;
309
+ return __generator(this, function (_c) {
310
+ switch (_c.label) {
311
+ case 0:
312
+ _c.trys.push([0, 20, , 21]);
313
+ prefix = '';
314
+ if (name.indexOf('before') === 0)
315
+ prefix = 'before';
316
+ if (name.indexOf('after') === 0)
317
+ prefix = 'after';
318
+ globalHookHandler = Table.hooks[name];
319
+ hookHandler = this.options.hooks && this.options.hooks[name];
320
+ if (!(args.data && prefix)) return [3 /*break*/, 15];
321
+ fields = Object.keys(args.data);
322
+ schema = mandarina_1.Schema.getInstance(schemaName);
323
+ _i = 0, fields_1 = fields;
324
+ _c.label = 1;
325
+ case 1:
326
+ if (!(_i < fields_1.length)) return [3 /*break*/, 15];
327
+ field = fields_1[_i];
328
+ def = schema.getPathDefinition(field);
329
+ inline = !!(def.table && def.table.relation && def.table.relation.link === 'INLINE');
330
+ if (!def.isTable) return [3 /*break*/, 14];
331
+ operations = Object.keys(args.data[field]);
332
+ if (!Table.instances[def.type]) {
333
+ //console.warn(`No table for ${def.type} no neasted hooks applied`)
334
+ return [3 /*break*/, 14];
309
335
  }
310
- }
311
- }
312
- if (globalHookHandler) {
313
- context.schemaName = schemaName;
314
- context.name = name;
315
- yield globalHookHandler(_, args, context, info);
316
- }
317
- if (hookHandler) {
318
- yield hookHandler(_, args, context, info);
336
+ table = Table.getInstance(def.type);
337
+ _a = 0, operations_1 = operations;
338
+ _c.label = 2;
339
+ case 2:
340
+ if (!(_a < operations_1.length)) return [3 /*break*/, 14];
341
+ operation = operations_1[_a];
342
+ hookName = "" + prefix + utils_1.capitalize(operation);
343
+ args2 = args.data[field][operation];
344
+ if (!Array.isArray(args2)) return [3 /*break*/, 9];
345
+ _b = 0, args2_1 = args2;
346
+ _c.label = 3;
347
+ case 3:
348
+ if (!(_b < args2_1.length)) return [3 /*break*/, 8];
349
+ arg2 = args2_1[_b];
350
+ if (!inline) return [3 /*break*/, 5];
351
+ return [4 /*yield*/, table.callHook(def.type, hookName, _, arg2.data ? arg2 : { data: arg2 }, context, info)];
352
+ case 4:
353
+ _c.sent();
354
+ return [3 /*break*/, 7];
355
+ case 5: return [4 /*yield*/, table.callHook(def.type, hookName, _, arg2.data ? arg2 : { data: arg2 }, context, info)];
356
+ case 6:
357
+ _c.sent();
358
+ _c.label = 7;
359
+ case 7:
360
+ _b++;
361
+ return [3 /*break*/, 3];
362
+ case 8: return [3 /*break*/, 13];
363
+ case 9:
364
+ if (!inline) return [3 /*break*/, 11];
365
+ return [4 /*yield*/, table.callHook(def.type, hookName, _, args2.data ? args2 : { data: args2 }, context, info)];
366
+ case 10:
367
+ _c.sent();
368
+ return [3 /*break*/, 13];
369
+ case 11: return [4 /*yield*/, table.callHook(def.type, hookName, _, args2.data ? args2 : { data: args2 }, context, info)];
370
+ case 12:
371
+ _c.sent();
372
+ _c.label = 13;
373
+ case 13:
374
+ _a++;
375
+ return [3 /*break*/, 2];
376
+ case 14:
377
+ _i++;
378
+ return [3 /*break*/, 1];
379
+ case 15:
380
+ if (!globalHookHandler) return [3 /*break*/, 17];
381
+ context.schemaName = schemaName;
382
+ context.name = name;
383
+ return [4 /*yield*/, globalHookHandler(_, args, context, info)];
384
+ case 16:
385
+ _c.sent();
386
+ _c.label = 17;
387
+ case 17:
388
+ if (!hookHandler) return [3 /*break*/, 19];
389
+ return [4 /*yield*/, hookHandler(_, args, context, info)];
390
+ case 18:
391
+ _c.sent();
392
+ _c.label = 19;
393
+ case 19: return [3 /*break*/, 21];
394
+ case 20:
395
+ e_1 = _c.sent();
396
+ console.error("Error executing hook: \"" + name + "\" in Table: " + schemaName + "\"");
397
+ console.error(e_1);
398
+ throw e_1;
399
+ case 21: return [2 /*return*/];
319
400
  }
320
- }
321
- catch (e) {
322
- console.error(`Error executing hook: "${name}" in Table: ${schemaName}"`);
323
- console.error(e);
324
- throw e;
325
- }
401
+ });
326
402
  });
327
- }
328
- }
403
+ };
404
+ Table.hooks = {};
405
+ Table.setGlobalHooks = function (hooks) {
406
+ Table.hooks = hooks;
407
+ };
408
+ return Table;
409
+ }());
329
410
  exports.Table = Table;
330
- Table.hooks = {};
331
- Table.setGlobalHooks = (hooks) => {
332
- Table.hooks = hooks;
333
- };
334
411
  // let time = new Date().getTime()
335
412
  // export function bm(description = '',...args:any) {
336
413
  // description && console.info(description,...args, new Date().getTime() - time)
337
414
  // time = new Date().getTime()
338
415
  //
339
416
  // }
340
- //# sourceMappingURL=Table.js.map
@@ -7,7 +7,7 @@ import {UniqueSchemaError} from 'mandarina/build/Errors/UniqueSchemaError';
7
7
  import {SchemaInstanceNotFound} from "mandarina/build/Errors/SchemaInstanceNotFound";
8
8
  import {capitalize} from 'mandarina/build/Schema/utils';
9
9
  import {MissingIdTableError} from "mandarina/build/Errors/MissingIDTableError";
10
- import {ErrorFromServerMapper} from "mandarina/src/Schema/Schema";
10
+ import {ErrorFromServerMapper} from "mandarina/build/Schema/Schema";
11
11
  import Mandarina, {UserType} from "../Mandarina";
12
12
  import {deepClone} from "mandarina/build/Operations/Mutate";
13
13
  import {parseValue, print, Source, visit} from 'graphql/language'
package/src/cli/utils.js CHANGED
@@ -1,12 +1,8 @@
1
1
  "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
2
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.loadSchemas = exports.getConfig = void 0;
7
- var fs_1 = __importDefault(require("fs"));
8
- var path_1 = __importDefault(require("path"));
9
- var getConfig = function () {
3
+ var fs_1 = require("fs");
4
+ var path_1 = require("path");
5
+ exports.getConfig = function () {
10
6
  var rawData;
11
7
  try {
12
8
  rawData = fs_1.default.readFileSync(path_1.default.join(process.cwd(), 'mandarina.json'), 'utf8');
@@ -35,7 +31,6 @@ var getConfig = function () {
35
31
  }
36
32
  return (config);
37
33
  };
38
- exports.getConfig = getConfig;
39
34
  var walkSync = function (dir, fileList) {
40
35
  var files = fs_1.default.readdirSync(dir);
41
36
  fileList = fileList || [];
@@ -51,7 +46,7 @@ var walkSync = function (dir, fileList) {
51
46
  });
52
47
  return fileList;
53
48
  };
54
- var loadSchemas = function (dir) {
49
+ exports.loadSchemas = function (dir) {
55
50
  var tables = [];
56
51
  var schemas = [];
57
52
  var actions = [];
@@ -90,5 +85,3 @@ var loadSchemas = function (dir) {
90
85
  }
91
86
  });
92
87
  };
93
- exports.loadSchemas = loadSchemas;
94
- //# sourceMappingURL=utils.js.map