UNPKG

shyft

Version:

Model driven GraphQL API framework

307 lines (306 loc) 14 kB
"use strict"; var __assign = (this && this.__assign) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { 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; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; Object.defineProperty(exports, "__esModule", { value: true }); exports.generateReverseConnections = exports.registerConnection = exports.connectionFromData = exports.buildCursor = exports.generateConnectionType = exports.forceSortByUnique = exports.validateConnectionArgs = exports.generateConnectionArgs = void 0; var graphql_1 = require("graphql"); var lodash_1 = require("lodash"); var dataTypes_1 = require("./dataTypes"); var resolver_1 = require("./resolver"); var ProtocolGraphQL_1 = require("./ProtocolGraphQL"); var sort_1 = require("./sort"); var filter_1 = require("./filter"); var registry_1 = require("./registry"); var generateConnectionArgs = function (entity, graphRegistry) { var sortInput = sort_1.generateSortInput(entity); var filterInput = filter_1.generateFilterInput(entity, graphRegistry); return { first: { type: graphql_1.GraphQLInt, }, after: { type: dataTypes_1.GraphQLCursor, }, last: { type: graphql_1.GraphQLInt, }, before: { type: dataTypes_1.GraphQLCursor, }, offset: { type: graphql_1.GraphQLInt, }, orderBy: __assign({}, sortInput), filter: __assign({}, filterInput), }; }; exports.generateConnectionArgs = generateConnectionArgs; var validateConnectionArgs = function (_source, args) { var protocolConfiguration = ProtocolGraphQL_1.ProtocolGraphQL.getProtocolConfiguration(); // const maxPageSize = protocolConfiguration.getMaxPageSize( // source, // args, // context, // info, // ); var maxPageSize = protocolConfiguration.getMaxPageSize(); if (args.first >= 0 && args.last >= 0) { throw new Error('`first` and `last` settings are mutual exclusive'); } if (args.first && (args.first < 0 || args.first > maxPageSize)) { throw new Error("`first` needs to be within the range of 0 and " + maxPageSize); } if (args.last && (args.last < 0 || args.last > maxPageSize)) { throw new Error("`last` needs to be within the range of 0 and " + maxPageSize); } if (args.offset && args.offset < 0) { throw new Error('`offset` needs to be an integer starting from 0'); } }; exports.validateConnectionArgs = validateConnectionArgs; var forceSortByUnique = function (orderBy, entity) { var attributes = entity.getAttributes(); var foundUnique = false; orderBy.map(function (_a) { var attribute = _a.attribute; var unique = attributes[attribute].unique; if (unique) { foundUnique = true; } }); if (!foundUnique) { if (entity.getPrimaryAttribute()) { var primaryAttribute = entity.getPrimaryAttribute(); orderBy.push({ attribute: primaryAttribute.name, direction: 'ASC', }); } } }; exports.forceSortByUnique = forceSortByUnique; var pageInfoType = new graphql_1.GraphQLObjectType({ name: 'PageInfo', description: 'Information about pagination in a connection.', fields: function () { return ({ hasNextPage: { type: new graphql_1.GraphQLNonNull(graphql_1.GraphQLBoolean), description: 'When paginating forwards, are there more items?', }, hasPreviousPage: { type: new graphql_1.GraphQLNonNull(graphql_1.GraphQLBoolean), description: 'When paginating backwards, are there more items?', }, startCursor: { type: dataTypes_1.GraphQLCursor, description: 'When paginating backwards, the cursor to continue.', }, endCursor: { type: dataTypes_1.GraphQLCursor, description: 'When paginating forwards, the cursor to continue.', }, }); }, }); var generateConnectionType = function (config) { // const protocolConfiguration = ProtocolGraphQL.getProtocolConfiguration(); var protocolConfiguration = ProtocolGraphQL_1.ProtocolGraphQL.getProtocolConfiguration(); var nodeType = config.nodeType, entity = config.entity; var typeNamePluralListName = registry_1.getRegisteredEntity(entity.name).typeNamePluralPascalCase; var cursor; if (entity.getPrimaryAttribute()) { cursor = { type: new graphql_1.GraphQLNonNull(dataTypes_1.GraphQLCursor), description: 'A cursor for use in pagination', }; } var edgeType = new graphql_1.GraphQLObjectType({ name: protocolConfiguration.generateConnectionEdgeTypeName(entity), description: 'An edge in a connection.', fields: function () { return (__assign({ node: { type: nodeType, description: 'The item at the end of the edge', } }, (cursor && { cursor: cursor }))); }, }); var connectionType = new graphql_1.GraphQLObjectType({ name: protocolConfiguration.generateConnectionTypeName(entity), description: 'A connection to a list of items.', fields: function () { return ({ pageInfo: { type: new graphql_1.GraphQLNonNull(pageInfoType), description: 'Information to aid in pagination.', }, edges: { type: new graphql_1.GraphQLList(edgeType), description: 'A list of edges.', }, totalCount: { type: graphql_1.GraphQLInt, description: "The count of all **`" + typeNamePluralListName + "`** you could get from the connection.", }, resultCount: { type: graphql_1.GraphQLInt, description: "The count of **`" + typeNamePluralListName + "`** in this result set.", resolve: function (_a) { var edges = _a.edges; return edges.length; }, }, }); }, }); return { edgeType: edgeType, connectionType: connectionType, }; }; exports.generateConnectionType = generateConnectionType; var buildCursor = function (entityName, primaryAttributeName, args, data) { var _a; var cursor = []; var primaryAttributeAdded = false; if (args && args.orderBy) { args.orderBy.map(function (_a) { var attribute = _a.attribute; cursor.push([attribute, data[attribute]]); if (attribute === primaryAttributeName) { primaryAttributeAdded = true; } }); } if (!primaryAttributeAdded) { cursor.push([primaryAttributeName, data[primaryAttributeName]]); } return _a = {}, _a[entityName] = cursor, _a; }; exports.buildCursor = buildCursor; var connectionFromData = function (_a, entity, _source, args, context, _info, parentConnection, pageInfoFromData) { var transformedData = _a.transformedData, originalData = _a.originalData; var entityName = entity.name; var nodeToEdge; if (entity.getPrimaryAttribute()) { var primaryAttributeName_1 = entity.getPrimaryAttribute().name; nodeToEdge = function (node, idx) { return ({ cursor: exports.buildCursor(entityName, primaryAttributeName_1, args, originalData[idx]), node: node, }); }; } else { nodeToEdge = function (node) { return ({ node: node, }); }; } var edges = transformedData.map(nodeToEdge); var firstNode = lodash_1.first(edges); var lastNode = lodash_1.last(edges); return { edges: edges, totalCount: function () { return __awaiter(void 0, void 0, void 0, function () { var storageType; return __generator(this, function (_a) { storageType = entity.storageType; return [2 /*return*/, storageType.count(entity, args, context, parentConnection)]; }); }); }, pageInfo: { startCursor: firstNode ? firstNode.cursor : null, endCursor: lastNode ? lastNode.cursor : null, hasPreviousPage: pageInfoFromData.hasPreviousPage, hasNextPage: pageInfoFromData.hasNextPage, }, }; }; exports.connectionFromData = connectionFromData; var registerConnection = function (graphRegistry, entity) { var typeName = registry_1.getRegisteredEntity(entity.name).typeName; var type = graphRegistry.types[typeName].type; var connectionType = exports.generateConnectionType({ nodeType: type, entity: entity, }).connectionType; var connectionArgs = exports.generateConnectionArgs(entity, graphRegistry); graphRegistry.types[typeName].connection = connectionType; graphRegistry.types[typeName].connectionArgs = connectionArgs; }; exports.registerConnection = registerConnection; var generateReverseConnections = function (configuration, graphRegistry, entity) { var schema = configuration.getSchema(); var schemaEntities = schema.getEntities(); var protocolConfiguration = ProtocolGraphQL_1.ProtocolGraphQL.getProtocolConfiguration(); var fields = {}; var typeNamePascalCase = registry_1.getRegisteredEntity(entity.name).typeNamePascalCase; entity.referencedByEntities.map(function (_a) { var sourceEntityName = _a.sourceEntityName, sourceAttributeName = _a.sourceAttributeName; var sourceEntity = schemaEntities[sourceEntityName]; if (!sourceEntity) { throw new Error("Failed to create reverse connection for entity '" + sourceEntityName + "' as it was not found"); } var sourceEntityTypeName = protocolConfiguration.generateEntityTypeName(sourceEntity); var fieldName = protocolConfiguration.generateReverseConnectionFieldName(sourceEntity, sourceAttributeName); var typeNamePluralListName = registry_1.getRegisteredEntity(sourceEntity.name).typeNamePluralPascalCase; fields[fieldName] = { type: graphRegistry.types[sourceEntityTypeName].connection, description: "Fetch a list of **`" + typeNamePluralListName + "`** for a given **`" + typeNamePascalCase + "`**\n" + (sourceEntity.descriptionPermissionsFind || ''), args: graphRegistry.types[sourceEntityTypeName].connectionArgs, resolve: resolver_1.resolveByFind(sourceEntity, function (_a) { var source = _a.source, info = _a.info; var parentEntityTypeName = protocolConfiguration.generateEntityTypeName(info.parentType); var parentEntity = graphRegistry.types[parentEntityTypeName].entity; var parentAttribute = parentEntity.getPrimaryAttribute(); var gqlFieldName = registry_1.getRegisteredEntityAttribute(parentEntity.name, parentAttribute.name).fieldName; var parentConnection = { id: source[gqlFieldName], attribute: sourceAttributeName, }; return parentConnection; }), }; }); return fields; }; exports.generateReverseConnections = generateReverseConnections;