UNPKG

@netlify/content-engine

Version:
717 lines 28.4 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.LocalNodeModel = void 0; const lodash_isempty_1 = __importDefault(require("lodash.isempty")); const lodash_pickby_1 = __importDefault(require("lodash.pickby")); const lodash_isplainobject_1 = __importDefault(require("lodash.isplainobject")); const lodash_merge_1 = __importDefault(require("lodash.merge")); const is_object_1 = require("../core-utils/is-object"); const graphql_1 = require("graphql"); const invariant_1 = __importDefault(require("invariant")); const reporter_1 = __importDefault(require("../reporter")); const redux_1 = require("../redux"); const datastore_1 = require("../datastore"); const iterable_1 = require("../datastore/common/iterable"); const detect_node_mutations_1 = require("../utils/detect-node-mutations"); const utils_1 = require("./utils"); const resolvers_1 = require("./resolvers"); const prefer_default_1 = require("../bootstrap/prefer-default"); class LocalNodeModel { constructor({ schema, schemaComposer, createPageDependency, _rootNodeMap, _trackedRootNodes, }) { // @ts-ignore this.schema = schema; // @ts-ignore this.schemaComposer = schemaComposer; // @ts-ignore this.createPageDependencyActionCreator = createPageDependency; // @ts-ignore this._rootNodeMap = _rootNodeMap || new WeakMap(); // @ts-ignore this._trackedRootNodes = _trackedRootNodes || new WeakSet(); // @ts-ignore this._prepareNodesQueues = {}; // @ts-ignore this._prepareNodesPromises = {}; // @ts-ignore this._preparedNodesCache = new Map(); this.replaceFiltersCache(); } createPageDependency() { } /** * Replace the cache either with the value passed on (mainly for tests) or * an empty new Map. * * @param {undefined | null | FiltersCache} map * This cache caches a set of buckets (Sets) of Nodes based on filter and tracks this for each set of types which are * actually queried. If the filter targets `id` directly, only one Node is * cached instead of a Set of Nodes. If null, don't create or use a cache. */ replaceFiltersCache(map = new Map()) { // @ts-ignore this._filtersCache = map; // See redux/nodes.js for usage } withContext(context) { return new ContextualNodeModel(this, context); } /** * Get a node from the store by ID and optional type. * * @param {Object} args * @param {string} args.id ID of the requested node * @param {(string|GraphQLOutputType)} [args.type] Optional type of the node * @param {PageDependencies} [pageDependencies] * @returns {(Node|null)} * @example * // Using only the id * getNodeById({ id: `123` }) * // Using id and type * getNodeById({ id: `123`, type: `MyType` }) * // Providing page dependencies * getNodeById({ id: `123` }, { path: `/` }) */ getNodeById(args, pageDependencies) { const { id, type } = args || {}; const node = getNodeById(id); let result; if (!node) { result = null; } else if (!type) { result = node; } else { // @ts-ignore const nodeTypeNames = (0, utils_1.toNodeTypeNames)(this.schema, type); result = nodeTypeNames.includes(node.internal.type) ? node : null; } // @ts-ignore return (0, detect_node_mutations_1.wrapNode)(this.trackPageDependencies(result, pageDependencies)); } /** * Get nodes from the store by IDs and optional type. * * @param {Object} args * @param {string[]} args.ids IDs of the requested nodes * @param {boolean} args.keepObjects wether to return mixed node/non-node objects * @param {(string|GraphQLOutputType)} [args.type] Optional type of the nodes * @returns {Node[]} * @example * // Using only the id * getNodeByIds({ ids: [`123`, `456`] }) * * // Using id and type * getNodeByIds({ ids: [`123`, `456`], type: `MyType` }) * * // Providing page dependencies * getNodeByIds({ ids: [`123`, `456`] }) */ getNodesByIds(args) { const { ids, type, keepObjects } = args || {}; const nodes = Array.isArray(ids) ? ids .map((id) => { if (typeof id === `string`) return getNodeById(id); if (keepObjects) { return id; } else { return null; } }) .filter(Boolean) : []; let result; if (!nodes.length || !type) { result = nodes; } else { const nodeTypeNames = (keepObjects ? utils_1.toTypeNames : utils_1.toNodeTypeNames)( // @ts-ignore this.schema, type); // @ts-ignore result = nodes.filter((node) => node?.internal?.type ? nodeTypeNames.includes(node.internal.type) : nodeTypeNames.includes(node?.__typename)); } return result; } async _query(args) { let { query = {}, type, stats, tracer } = args || {}; // We don't support querying union types (yet?), because the combined types // need not have any fields in common. // @ts-ignore const gqlType = typeof type === `string` ? this.schema.getType(type) : type; (0, invariant_1.default)(!(gqlType instanceof graphql_1.GraphQLUnionType), `Querying GraphQLUnion types is not supported.`); // @ts-ignore const nodeTypeNames = (0, utils_1.toNodeTypeNames)(this.schema, gqlType); let runQueryActivity; // check if we can get node by id and skip // more expensive query pipeline if (typeof query?.filter?.id?.eq !== `undefined` && Object.keys(query.filter).length === 1 && Object.keys(query.filter.id).length === 1) { if (tracer) { runQueryActivity = reporter_1.default.phantomActivity(`runQuerySimpleIdEq`, { parentSpan: tracer.getParentActivity().span, }); runQueryActivity.start(); } // @ts-ignore const nodeFoundById = this.getNodeById({ id: query.filter.id.eq, type: gqlType, }); if (runQueryActivity) { runQueryActivity.end(); } return { gqlType, entries: new iterable_1.GatsbyIterable(nodeFoundById ? [nodeFoundById] : []), totalCount: async () => (nodeFoundById ? 1 : 0), }; } query = (0, utils_1.maybeConvertSortInputObjectToSortPath)(query); let materializationActivity; if (tracer) { materializationActivity = reporter_1.default.phantomActivity(`Materialization`, { parentSpan: tracer.getParentActivity().span, }); materializationActivity.start(); } const fields = getQueryFields({ filter: query.filter, sort: query.sort, group: query.group, distinct: query.distinct, max: query.max, min: query.min, sum: query.sum, }); const fieldsToResolve = determineResolvableFields( // @ts-ignore this.schemaComposer, // @ts-ignore this.schema, gqlType, fields); for (const nodeTypeName of nodeTypeNames) { // @ts-ignore const gqlNodeType = this.schema.getType(nodeTypeName); await this.prepareNodes(gqlNodeType, fields, fieldsToResolve); } if (materializationActivity) { materializationActivity.end(); } if (tracer) { runQueryActivity = reporter_1.default.phantomActivity(`runQuery`, { parentSpan: tracer.getParentActivity().span, }); runQueryActivity.start(); } const { entries, totalCount } = await (0, datastore_1.getDataStore)().runQuery({ queryArgs: query, // @ts-ignore gqlSchema: this.schema, // @ts-ignore gqlComposer: this.schemaComposer, gqlType, resolvedFields: fieldsToResolve, nodeTypeNames, // @ts-ignore filtersCache: this._filtersCache, stats, }); if (runQueryActivity) { runQueryActivity.end(); } return { gqlType, entries: entries.map((node) => { // With GatsbyIterable it happens lazily as we iterate return node; }), totalCount, }; } /** * Get all nodes in the store, or all nodes of a specified type (optionally with limit/skip). * Returns slice of result as iterable and total count of nodes. * * You can directly return its `entries` result in your resolver. * * @param {*} args * @param {Object} args.query Query arguments (e.g. `limit` and `skip`) * @param {(string|GraphQLOutputType)} args.type Type * @param {PageDependencies} [pageDependencies] * @return {Promise<Object>} Object containing `{ entries: GatsbyIterable, totalCount: () => Promise<number> }` * @example * // Get all nodes of a type * const { entries, totalCount } = await findAll({ type: `MyType` }) * * // Get all nodes of a type while filtering and sorting * const { entries, totalCount } = await findAll({ * type: `MyType`, * query: { * sort: { fields: [`date`], order: [`desc`] }, * filter: { published: { eq: false } }, * }, * }) * * // The `entries` return value is a `GatsbyIterable` (check its TypeScript definition for more details) and allows you to execute array like methods like filter, map, slice, forEach. Calling these methods is more performant than first turning the iterable into an array and then calling the array methods. * const { entries, totalCount } = await findAll({ type: `MyType` }) * * const count = await totalCount() * const filteredEntries = entries.filter(entry => entry.published) * * // However, if a method is not available on the `GatsbyIterable` you can turn it into an array first. * const filteredEntries = entries.filter(entry => entry.published) * return Array.from(posts).length */ async findAll(args) { const { gqlType, ...result } = await this._query(args); this.trackPageDependencies(result.entries); return { // @ts-ignore entries: (0, detect_node_mutations_1.wrapNodes)(result.entries), totalCount: result.totalCount, }; } /** * Get one node in the store. Only returns the first result. When possible, always use this method instead of fetching all nodes and then filtering them. `findOne` is more performant in that regard. * * @param {*} args * @param {Object} args.query Query arguments (e.g. `filter`). Doesn't support `sort`, `limit`, `skip`. * @param {(string|GraphQLOutputType)} args.type Type * @param {PageDependencies} [pageDependencies] * @returns {Promise<Node>} * @example * // Get one node of type `MyType` by its title * const node = await findOne({ * type: `MyType`, * query: { filter: { title: { eq: `My Title` } } }, * }) */ async findOne(args, pageDependencies = {}) { const { query = {} } = args; if (query.sort?.fields?.length > 0) { // If we support sorting and return the first node based on sorting // we'll have to always track connection not an individual node throw new Error(`nodeModel.findOne() does not support sorting. Use nodeModel.findAll({ query: { limit: 1 } }) instead.`); } const { entries } = await this._query({ ...args, query: { ...query, skip: 0, limit: 1, sort: undefined }, }); const result = Array.from(entries); const first = result[0] ?? null; // @ts-ignore return (0, detect_node_mutations_1.wrapNode)(this.trackPageDependencies(first, pageDependencies)); } prepareNodes(type, queryFields, fieldsToResolve) { const typeName = type.name; // @ts-ignore if (!this._prepareNodesQueues[typeName]) { // @ts-ignore this._prepareNodesQueues[typeName] = []; } // @ts-ignore this._prepareNodesQueues[typeName].push({ queryFields, fieldsToResolve, }); // @ts-ignore if (!this._prepareNodesPromises[typeName]) { // @ts-ignore this._prepareNodesPromises[typeName] = new Promise((resolve) => { process.nextTick(async () => { await this._doResolvePrepareNodesQueue(type); resolve(null); }); }); } // @ts-ignore return this._prepareNodesPromises[typeName]; } async _doResolvePrepareNodesQueue(type) { const typeName = type.name; // @ts-ignore const queue = this._prepareNodesQueues[typeName]; // @ts-ignore this._prepareNodesQueues[typeName] = []; // @ts-ignore this._prepareNodesPromises[typeName] = null; const { queryFields, fieldsToResolve } = queue.reduce(({ queryFields, fieldsToResolve }, { queryFields: nextQueryFields, fieldsToResolve: nextFieldsToResolve }) => { return { queryFields: (0, lodash_merge_1.default)(queryFields, nextQueryFields), fieldsToResolve: (0, lodash_merge_1.default)(fieldsToResolve, nextFieldsToResolve), }; }, { queryFields: {}, fieldsToResolve: {}, }); const actualFieldsToResolve = deepObjectDifference(fieldsToResolve, // @ts-ignore this._preparedNodesCache.get(typeName) || {}); if (!(0, lodash_isempty_1.default)(actualFieldsToResolve)) { const { schemaCustomization: { context: customContext }, } = redux_1.store.getState(); const resolvedNodes = new Map(); for (const node of (0, datastore_1.getDataStore)().iterateNodesByType(typeName)) { const resolvedFields = await resolveRecursive(this, // @ts-ignore this.schemaComposer, // @ts-ignore this.schema, node, type, queryFields, actualFieldsToResolve, customContext); resolvedNodes.set(node.id, resolvedFields); } if (resolvedNodes.size) { await saveResolvedNodes(typeName, resolvedNodes); } // @ts-ignore this._preparedNodesCache.set(typeName, (0, lodash_merge_1.default)({}, // @ts-ignore this._preparedNodesCache.get(typeName) || {}, actualFieldsToResolve)); } } /** * Get the names of all node types in the store. * * @returns {string[]} */ getTypes() { return (0, datastore_1.getTypes)(); } /** * Finds top most ancestor of node that contains passed Object or Array * @param {(Object|Array)} obj Object/Array belonging to Node object or Node object * @param {nodePredicate} [predicate] Optional callback to check if ancestor meets defined conditions * @returns {Node} Top most ancestor if predicate is not specified * or first node that meet predicate conditions if predicate is specified */ findRootNodeAncestor(obj, predicate = null) { let iterations = 0; // @ts-ignore let ids = this._rootNodeMap.get(obj); if (!ids) { ids = []; } if (obj?.parent) { ids.push(obj.parent); } let matchingRoot = null; if (ids) { for (const id of ids) { let tracked = getNodeById(id); if (tracked) { const visited = new Set(); while (iterations++ < 100) { // @ts-ignore if (predicate && predicate(tracked)) { return tracked; } if (visited.has(tracked)) { reporter_1.default.error(`It looks like you have a node that's set its parent as itself:\n\n` + tracked); break; } visited.add(tracked); const parent = getNodeById(tracked.parent); if (!parent) { break; } tracked = parent; } if (tracked && !predicate) { // @ts-ignore matchingRoot = tracked; } } } } return matchingRoot; } /** * Given a result, that's either a single node or an array of them, track them * using pageDependencies. Defaults to tracking according to current resolver * path. Returns the result back. * * @param {Node | Node[]} result * @param {PageDependencies} [pageDependencies] * @returns {Node | Node[]} */ trackPageDependencies(result) { return result; } /** * Utility to get a field value from a node, even when that value needs to be materialized first (e.g. nested field that was connected via @link directive) * @param {Node} node * @param {string} fieldPath * @returns {any} * @example * // Example: Via schema customization the author ID is linked to the Author type * const blogPostNode = { * author: 'author-id-1', * // Rest of node fields... * } * * getFieldValue(blogPostNode, 'author.name') */ getFieldValue = async (node, fieldPath) => { const fieldToResolve = pathToObject(fieldPath); const typeName = node.internal.type; // @ts-ignore const type = this.schema.getType(typeName); await this.prepareNodes(type, fieldToResolve, fieldToResolve); return (0, resolvers_1.getMaybeResolvedValue)(node, fieldPath, typeName); }; } exports.LocalNodeModel = LocalNodeModel; class ContextualNodeModel { constructor(rootNodeModel, context) { // @ts-ignore this.nodeModel = rootNodeModel; // @ts-ignore this.context = context; } withContext(context) { // @ts-ignore return new ContextualNodeModel(this.nodeModel, { // @ts-ignore ...this.context, ...context, }); } _getFullDependencies(pageDependencies) { return { // @ts-ignore path: this.context.path, ...(pageDependencies || {}), }; } getNodeById(args, pageDependencies) { // @ts-ignore return this.nodeModel.getNodeById(args, this._getFullDependencies(pageDependencies)); } getNodesByIds(args, pageDependencies) { // @ts-ignore return this.nodeModel.getNodesByIds(args, this._getFullDependencies(pageDependencies)); } findOne(args, pageDependencies) { // @ts-ignore return this.nodeModel.findOne(args, this._getFullDependencies(pageDependencies)); } findAll(args, pageDependencies) { // @ts-ignore return this.nodeModel.findAll(args, this._getFullDependencies(pageDependencies)); } prepareNodes(...args) { // @ts-ignore return this.nodeModel.prepareNodes(...args); } getTypes(...args) { // @ts-ignore return this.nodeModel.getTypes(...args); } findRootNodeAncestor(...args) { // @ts-ignore return this.nodeModel.findRootNodeAncestor(...args); } createPageDependency(...args) { // @ts-ignore return this.nodeModel.createPageDependency(...args); } trackPageDependencies(result, pageDependencies) { // @ts-ignore return this.nodeModel.trackPageDependencies(result, this._getFullDependencies(pageDependencies)); } // @ts-ignore getFieldValue = (...args) => this.nodeModel.getFieldValue(...args); } const getNodeById = (id) => (id != null ? (0, datastore_1.getNode)(id) : null); const getQueryFields = ({ filter, sort, group, distinct, max, min, sum }) => { const filterFields = filter ? dropQueryOperators(filter) : {}; const sortFields = (sort && sort.fields) || []; if (group && !Array.isArray(group)) { group = [group]; } else if (group == null) { group = []; } if (distinct && !Array.isArray(distinct)) { distinct = [distinct]; } else if (distinct == null) { distinct = []; } if (max && !Array.isArray(max)) { max = [max]; } else if (max == null) { max = []; } if (min && !Array.isArray(min)) { min = [min]; } else if (min == null) { min = []; } if (sum && !Array.isArray(sum)) { sum = [sum]; } else if (sum == null) { sum = []; } return (0, lodash_merge_1.default)(filterFields, ...sortFields.map(pathToObject), ...group.map(pathToObject), ...distinct.map(pathToObject), ...max.map(pathToObject), ...min.map(pathToObject), ...sum.map(pathToObject)); }; const pathToObject = (path) => { if (path && typeof path === `string`) { // @ts-ignore return path.split(`.`).reduceRight((acc, key) => { return { [key]: acc }; }, true); } return {}; }; const dropQueryOperators = (filter) => Object.keys(filter).reduce((acc, key) => { const value = filter[key]; const k = Object.keys(value)[0]; const v = value[k]; if ((0, lodash_isplainobject_1.default)(value) && (0, lodash_isplainobject_1.default)(v)) { acc[key] = k === `elemMatch` ? dropQueryOperators(v) : dropQueryOperators(value); } else { acc[key] = true; } return acc; }, {}); const getFields = (schema, type, node) => { if (!(0, graphql_1.isAbstractType)(type)) { return type.getFields(); } // @ts-ignore const concreteType = type.resolveType(node); return schema.getType(concreteType).getFields(); }; async function resolveRecursive(nodeModel, schemaComposer, schema, node, type, queryFields, fieldsToResolve, customContext) { const gqlFields = getFields(schema, type, node); const resolvedFields = {}; for (const fieldName of Object.keys(fieldsToResolve)) { const fieldToResolve = fieldsToResolve[fieldName]; const queryField = queryFields[fieldName]; const gqlField = gqlFields[fieldName]; const gqlNonNullType = (0, graphql_1.getNullableType)(gqlField.type); const gqlFieldType = (0, graphql_1.getNamedType)(gqlField.type); let innerValue = await resolveField(nodeModel, schemaComposer, schema, node, gqlField, fieldName, customContext); if (gqlField && innerValue != null) { if ((0, graphql_1.isCompositeType)(gqlFieldType) && !(gqlNonNullType instanceof graphql_1.GraphQLList)) { innerValue = await resolveRecursive(nodeModel, schemaComposer, schema, innerValue, gqlFieldType, queryField, (0, is_object_1.isObject)(fieldToResolve) ? fieldToResolve : queryField, customContext); } else if ((0, graphql_1.isCompositeType)(gqlFieldType) && (Array.isArray(innerValue) || innerValue instanceof iterable_1.GatsbyIterable) && gqlNonNullType instanceof graphql_1.GraphQLList) { innerValue = await Promise.all(innerValue.map((item) => item == null ? item : resolveRecursive(nodeModel, schemaComposer, schema, item, gqlFieldType, queryField, (0, is_object_1.isObject)(fieldToResolve) ? fieldToResolve : queryField, customContext))); } } if (innerValue != null) { resolvedFields[fieldName] = innerValue; } } for (const fieldName of Object.keys(queryFields)) { if (!fieldsToResolve[fieldName] && node[fieldName]) { // It is possible that this field still has a custom resolver // See https://github.com/gatsbyjs/gatsby/issues/27368 resolvedFields[fieldName] = await resolveField(nodeModel, schemaComposer, schema, node, gqlFields[fieldName], fieldName, customContext); } } // @ts-ignore return (0, lodash_pickby_1.default)(resolvedFields, (value, key) => queryFields[key]); } let withResolverContext; function resolveField(nodeModel, schemaComposer, schema, node, gqlField, fieldName, customContext) { if (!gqlField?.resolve) { return node[fieldName]; } // We require this inline as there's a circular dependency from context back to this file. // https://github.com/gatsbyjs/gatsby/blob/9d33b107d167e3e9e2aa282924a0c409f6afd5a0/packages/gatsby/src/schema/context.ts#L5 if (!withResolverContext) { withResolverContext = (0, prefer_default_1.preferDefault)(require(`./context`)); } return gqlField.resolve(node, gqlField.args.reduce((acc, arg) => { acc[arg.name] = arg.defaultValue; return acc; }, {}), withResolverContext({ schema, schemaComposer, nodeModel, customContext, }), { fieldName, schema, returnType: gqlField.type, }); } const determineResolvableFields = (schemaComposer, schema, type, fields, isNestedAndParentNeedsResolve = false) => { const fieldsToResolve = {}; const gqlFields = type.getFields(); Object.keys(fields).forEach((fieldName) => { const field = fields[fieldName]; const gqlField = gqlFields[fieldName]; const gqlFieldType = (0, graphql_1.getNamedType)(gqlField.type); const typeComposer = schemaComposer.getAnyTC(type.name); const needsResolve = (0, utils_1.fieldNeedToResolve)({ schema, gqlType: type, typeComposer, schemaComposer, fieldName, }); if ((0, is_object_1.isObject)(field) && gqlField) { const innerResolved = determineResolvableFields(schemaComposer, schema, gqlFieldType, field, isNestedAndParentNeedsResolve || needsResolve); if (!(0, lodash_isempty_1.default)(innerResolved)) { fieldsToResolve[fieldName] = innerResolved; } } if (!fieldsToResolve[fieldName] && needsResolve) { fieldsToResolve[fieldName] = true; } if (!fieldsToResolve[fieldName] && isNestedAndParentNeedsResolve) { // If parent field needs to be resolved - all nested fields should be added as well // See https://github.com/gatsbyjs/gatsby/issues/26056 fieldsToResolve[fieldName] = true; } }); return fieldsToResolve; }; const saveResolvedNodes = (typeName, resolvedNodes) => { redux_1.store.dispatch({ type: `SET_RESOLVED_NODES`, payload: { key: typeName, nodes: resolvedNodes, }, }); }; const deepObjectDifference = (from, to) => { const result = {}; Object.keys(from).forEach((key) => { const toValue = to[key]; if (toValue) { if ((0, lodash_isplainobject_1.default)(toValue)) { const deepResult = deepObjectDifference(from[key], toValue); if (!(0, lodash_isempty_1.default)(deepResult)) { result[key] = deepResult; } } } else { result[key] = from[key]; } }); return result; }; //# sourceMappingURL=node-model.js.map