UNPKG

@prismicio/client

Version:

The official JavaScript + TypeScript client library for Prismic

1 lines 13.5 kB
{"version":3,"file":"buildQueryURL.cjs","names":["devMsg","version"],"sources":["../src/buildQueryURL.ts"],"sourcesContent":["import { devMsg } from \"./lib/devMsg\"\n\nimport { version } from \"../package.json\"\n\n/**\n * The query parameter used to indicate if the client is in development mode to\n * the API.\n */\nconst PRISMIC_DEV_PARAM = \"x-d\"\n\n/** The query parameter used to indicate the version of the client to the API. */\nconst PRISMIC_CLIENT_VERSION_PARAM = \"x-c\"\n\n/**\n * Create a union of the given object's values, and optionally specify which\n * keys to get the values from.\n *\n * Taken from the `type-fest` package.\n *\n * See:\n * https://github.com/sindresorhus/type-fest/blob/61c35052f09caa23de5eef96d95196375d8ed498/source/value-of.d.ts\n */\ntype ValueOf<\n\tObjectType,\n\tValueType extends keyof ObjectType = keyof ObjectType,\n> = ObjectType[ValueType]\n\n/**\n * An `orderings` parameter that orders the results by the specified field.\n *\n * {@link https://prismic.io/docs/rest-api-technical-reference#orderings}\n */\nexport interface Ordering {\n\tfield: string\n\tdirection?: \"asc\" | \"desc\"\n}\n\n/**\n * A `routes` parameter that determines how a page's URL field is resolved.\n *\n * {@link https://prismic.io/docs/route-resolver}\n *\n * @example With a page's UID field.\n *\n * ```ts\n * {\n * \t\"type\": \"page\",\n * \t\"path\": \"/:uid\"\n * }\n * ```\n *\n * @example With a Content Relationship `parent` field.\n *\n * ```ts\n * {\n * \t\"type\": \"page\",\n * \t\"path\": \"/:parent?/:uid\",\n * \t\"resolvers\": {\n * \t\t\"parent\": \"parent\"\n * \t}\n * }\n * ```\n */\nexport interface Route {\n\t/** The custom type of the page. */\n\ttype: string\n\n\t/**\n\t * A specific UID to which this route definition is scoped. The route is only\n\t * defined for the page whose UID matches the given UID.\n\t */\n\tuid?: string\n\n\t/**\n\t * A specific language to which this route definition is scoped. The route is\n\t * only defined for pages whose language matches the given language.\n\t */\n\tlang?: string\n\n\t/** The resolved path of the page with optional placeholders. */\n\tpath: string\n\n\t/** An object that lists the API IDs of the Content Relationships in the route. */\n\tresolvers?: Record<string, string>\n}\n\n/**\n * Parameters for the Prismic Content API.\n *\n * @see Learn how to fetch content from Prismic: {@link https://prismic.io/docs/fetch-content}\n */\nexport interface QueryParams {\n\t/**\n\t * The secure token for accessing the API (only needed if your repository is\n\t * set to private).\n\t *\n\t * {@link https://prismic.io/docs/access-token}\n\t */\n\taccessToken?: string\n\n\t/**\n\t * The `pageSize` parameter defines the maximum number of pages that the API\n\t * will return for your query.\n\t *\n\t * {@link https://prismic.io/docs/rest-api-technical-reference#pagesize}\n\t */\n\tpageSize?: number\n\n\t/**\n\t * The `page` parameter defines the pagination for the result of your query.\n\t *\n\t * {@link https://prismic.io/docs/rest-api-technical-reference#page}\n\t */\n\tpage?: number\n\n\t/**\n\t * The `after` parameter can be used along with the orderings option. It will\n\t * remove all the pages except for those after the specified page in the\n\t * list.\n\t *\n\t * {@link https://prismic.io/docs/rest-api-technical-reference#after}\n\t */\n\tafter?: string\n\n\t/**\n\t * The `fetch` parameter is used to make queries faster by only retrieving the\n\t * specified field(s).\n\t *\n\t * {@link https://prismic.io/docs/rest-api-technical-reference#fetch}\n\t */\n\tfetch?: string | string[]\n\n\t/**\n\t * The `fetchLinks` parameter allows you to retrieve a specific content field\n\t * from a linked page and add it to the page response object.\n\t *\n\t * {@link https://prismic.io/docs/rest-api-technical-reference#fetchlinks}\n\t */\n\tfetchLinks?: string | string[]\n\n\t/**\n\t * The `graphQuery` parameter allows you to specify which fields to retrieve\n\t * and what content to retrieve from Linked Documents / Content\n\t * Relationships.\n\t *\n\t * {@link https://prismic.io/docs/graphquery-rest-api}\n\t */\n\tgraphQuery?: string\n\n\t/**\n\t * The `lang` option defines the language code for the results of your query.\n\t *\n\t * {@link https://prismic.io/docs/rest-api-technical-reference#lang}\n\t */\n\tlang?: string\n\n\t/**\n\t * The `orderings` parameter orders the results by the specified field(s). You\n\t * can specify as many fields as you want.\n\t *\n\t * {@link https://prismic.io/docs/rest-api-technical-reference#orderings}\n\t *\n\t * @remarks\n\t * Strings and arrays of strings are deprecated as of\n\t * `@prismicio/client@7.0.0`. Please migrate to the more explicit array of\n\t * objects.\n\t *\n\t * @example\n\t *\n\t * ```typescript\n\t * buildQueryURL(endpoint, {\n\t * \torderings: [\n\t * \t\t{ field: \"my.product.price\", direction: \"desc\" },\n\t * \t\t{ field: \"my.product.title\" },\n\t * \t],\n\t * })\n\t * ```\n\t */\n\t// TODO: Update TSDoc with deprecated API removal in v8\n\torderings?: string | Ordering | (string | Ordering)[]\n\n\t/**\n\t * The `routes` option allows you to define how a page's `url` field is\n\t * resolved.\n\t *\n\t * {@link https://prismic.io/docs/route-resolver}\n\t */\n\troutes?: Route | string | (Route | string)[]\n\n\t/**\n\t * The `brokenRoute` option allows you to define the route populated in the\n\t * `url` property for broken link or content relationship fields. A broken\n\t * link is a link or content relationship field whose linked page has been\n\t * unpublished or deleted.\n\t *\n\t * {@link https://prismic.io/docs/route-resolver}\n\t */\n\tbrokenRoute?: string\n}\n\n/** Arguments for `buildQueryURL` to construct a Query URL. */\ntype BuildQueryURLParams = {\n\t/**\n\t * Ref used to query documents.\n\t *\n\t * {@link https://prismic.io/docs/api#refs-and-the-entry-api}\n\t */\n\tref: string\n\n\t/**\n\t * Ref used to populate integration fields with the latest content.\n\t *\n\t * {@link https://prismic.io/docs/integration-fields}\n\t */\n\tintegrationFieldsRef?: string\n\n\t/**\n\t * One or more filters to filter documents for the query.\n\t *\n\t * {@link https://prismic.io/docs/rest-api-technical-reference#q}\n\t */\n\tfilters?: string | string[]\n\n\t/**\n\t * @deprecated Renamed to `filters`. Ensure the value is an array of filters,\n\t * not a single, non-array filter.\n\t */\n\tpredicates?: string | string[]\n}\n\n/**\n * Parameters in this map have been renamed from the official Prismic REST API\n * V2 specification for better developer ergonomics.\n *\n * These parameters are renamed to their mapped value.\n */\nconst RENAMED_PARAMS = {\n\taccessToken: \"access_token\",\n} as const\n\n/** A valid parameter name for the Prismic REST API V2. */\ntype ValidParamName =\n\t| Exclude<\n\t\t\tkeyof QueryParams,\n\t\t\tkeyof typeof RENAMED_PARAMS | keyof BuildQueryURLParams\n\t >\n\t| ValueOf<typeof RENAMED_PARAMS>\n\n/**\n * Converts an Ordering to a string that is compatible with Prismic's REST API.\n * If the value provided is already a string, no conversion is performed.\n *\n * @param ordering - Ordering to convert.\n *\n * @returns String representation of the Ordering.\n */\nconst castOrderingToString = (ordering: Ordering | string): string => {\n\t// TODO: Remove the following when `orderings` strings are no longer supported.\n\tif (typeof ordering === \"string\") {\n\t\tif (process.env.NODE_ENV === \"development\") {\n\t\t\tconst [field, direction] = ordering.split(\" \")\n\n\t\t\tconst objectForm =\n\t\t\t\tdirection === \"desc\"\n\t\t\t\t\t? `{ field: \"${field}\", direction: \"desc\" }`\n\t\t\t\t\t: `{ field: \"${field}\" }`\n\n\t\t\tconsole.warn(\n\t\t\t\t`[@prismicio/client] A string value was provided to the \\`orderings\\` query parameter. Strings are deprecated. Please convert it to the object form: ${objectForm}. For more details, see ${devMsg(\n\t\t\t\t\t\"orderings-must-be-an-array-of-objects\",\n\t\t\t\t)}`,\n\t\t\t)\n\t\t}\n\n\t\treturn ordering\n\t}\n\n\treturn ordering.direction === \"desc\"\n\t\t? `${ordering.field} desc`\n\t\t: ordering.field\n}\n\nexport type BuildQueryURLArgs = QueryParams & BuildQueryURLParams\n\n/**\n * Builds a Prismic Content API URL to request pages from a repository. The\n * paginated response for this URL includes pages matching the parameters.\n *\n * A ref is required to make a request. Request the `endpoint` URL to retrieve a\n * list of available refs.\n *\n * Type the JSON response with `Query`.\n *\n * @example\n *\n * ```ts\n * const url = buildQueryURL(\"https://my-repo.cdn.prismic.io/api/v2\", {\n * \tref: \"my-ref\",\n * \tfilters: [filter.at(\"document.type\", \"blog_post\")],\n * })\n * ```\n *\n * @param endpoint - URL to the repository's Content API.\n * @param args - Arguments to filter and scope the query.\n *\n * @returns URL that can be used to request pages from the repository.\n *\n * @see Prismic Content API technical reference: {@link https://prismic.io/docs/content-api}\n */\nexport const buildQueryURL = (\n\tendpoint: string,\n\targs: BuildQueryURLArgs,\n): string => {\n\tconst { filters, predicates, ...params } = args\n\n\tif (!endpoint.endsWith(\"/\")) {\n\t\tendpoint += \"/\"\n\t}\n\tconst url = new URL(`documents/search`, endpoint)\n\n\tif (filters) {\n\t\t// TODO: Remove warning when we remove support for string `filters` values.\n\t\tif (process.env.NODE_ENV === \"development\" && !Array.isArray(filters)) {\n\t\t\tconsole.warn(\n\t\t\t\t`[@prismicio/client] A non-array value was provided to the \\`filters\\` query parameter (\\`${filters}\\`). Non-array values are deprecated. Please convert it to an array. For more details, see ${devMsg(\n\t\t\t\t\t\"filters-must-be-an-array\",\n\t\t\t\t)}`,\n\t\t\t)\n\t\t}\n\n\t\t// TODO: Remove `castArray` when we remove support for string `filters` values.\n\t\tfor (const filter of castArray(filters)) {\n\t\t\turl.searchParams.append(\"q\", `[${filter}]`)\n\t\t}\n\t}\n\n\t// TODO: Remove when we remove support for deprecated `predicates` argument.\n\tif (predicates) {\n\t\tfor (const predicate of castArray(predicates)) {\n\t\t\turl.searchParams.append(\"q\", `[${predicate}]`)\n\t\t}\n\t}\n\n\t// Iterate over each parameter and add it to the URL. In some cases, the\n\t// parameter value needs to be transformed to fit the REST API.\n\tfor (const k in params) {\n\t\tconst name = (RENAMED_PARAMS[k as keyof typeof RENAMED_PARAMS] ||\n\t\t\tk) as ValidParamName\n\n\t\tlet value = params[k as keyof typeof params]\n\n\t\tif (name === \"orderings\") {\n\t\t\tconst scopedValue = params[name]\n\n\t\t\tif (scopedValue != null) {\n\t\t\t\t// TODO: Remove the following warning when `orderings` strings are no longer supported.\n\t\t\t\tif (\n\t\t\t\t\tprocess.env.NODE_ENV === \"development\" &&\n\t\t\t\t\ttypeof scopedValue === \"string\"\n\t\t\t\t) {\n\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\t`[@prismicio/client] A string value was provided to the \\`orderings\\` query parameter. Strings are deprecated. Please convert it to an array of objects. For more details, see ${devMsg(\n\t\t\t\t\t\t\t\"orderings-must-be-an-array-of-objects\",\n\t\t\t\t\t\t)}`,\n\t\t\t\t\t)\n\t\t\t\t}\n\n\t\t\t\tconst v = castArray(scopedValue)\n\t\t\t\t\t.map((ordering) => castOrderingToString(ordering))\n\t\t\t\t\t.join(\",\")\n\n\t\t\t\tvalue = `[${v}]`\n\t\t\t}\n\t\t} else if (name === \"routes\") {\n\t\t\tif (typeof params[name] === \"object\") {\n\t\t\t\tvalue = JSON.stringify(castArray(params[name]))\n\t\t\t}\n\t\t}\n\n\t\tif (value != null) {\n\t\t\turl.searchParams.set(\n\t\t\t\tname,\n\t\t\t\tcastArray<string | number | Route | Ordering>(value).join(\",\"),\n\t\t\t)\n\t\t}\n\t}\n\n\turl.searchParams.set(PRISMIC_CLIENT_VERSION_PARAM, `js-${version}`)\n\n\tif (process.env.NODE_ENV === \"development\") {\n\t\turl.searchParams.set(PRISMIC_DEV_PARAM, \"1\")\n\t}\n\n\treturn url.toString()\n}\n\nfunction castArray<A>(a: A | A[]): A[] {\n\treturn Array.isArray(a) ? a : [a]\n}\n"],"mappings":";;;;;;;;AAQA,MAAM,oBAAoB;;AAG1B,MAAM,+BAA+B;;;;;;;AAiOrC,MAAM,iBAAiB,EACtB,aAAa,gBACb;;;;;;;;;AAkBD,MAAM,wBAAwB,aAAwC;AAErE,KAAI,OAAO,aAAa,UAAU;AACjC,MAAI,QAAQ,IAAI,aAAa,eAAe;GAC3C,MAAM,CAAC,OAAO,aAAa,SAAS,MAAM,IAAI;GAE9C,MAAM,aACL,cAAc,SACX,aAAa,MAAM,0BACnB,aAAa,MAAM;AAEvB,WAAQ,KACP,uJAAuJ,WAAW,0BAA0BA,sBAC3L,wCACA,GACD;;AAGF,SAAO;;AAGR,QAAO,SAAS,cAAc,SAC3B,GAAG,SAAS,MAAM,SAClB,SAAS;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8Bb,MAAa,iBACZ,UACA,SACY;CACZ,MAAM,EAA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