Skip to content

Commit

Permalink
docs: add TSDocs to remaining functions
Browse files Browse the repository at this point in the history
  • Loading branch information
angeloashmore committed May 10, 2021
1 parent 7cb449a commit 38052d2
Show file tree
Hide file tree
Showing 6 changed files with 157 additions and 10 deletions.
101 changes: 99 additions & 2 deletions src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,45 +6,123 @@ import { buildQueryURL, BuildQueryURLArgs } from './buildQueryURL'
import * as cookie from './cookie'
import * as predicate from './predicate'

/**
* The minimum required properties to treat as an HTTP Request for automatic Prismic preview support.
*/
interface HttpRequestLike {
headers?: {
cookie?: string
}
query?: Record<string, unknown>
}

/**
* A ref or a function that returns a ref. If a static ref is known, one can be given. If the ref must be fetched on-demand, a function can be provided. This function can optionally be asynchronous.
*/
type RefStringOrFn =
| string
| (() => string | undefined | Promise<string | undefined>)

type Fetch = typeof fetch
/**
* A universal API to make network requests.
*/
type Fetch = typeof globalThis.fetch

/**
* Configuration for clients that determine how content is queried.
*/
export type ClientConfig = {
/**
* The secure token for accessing the Prismic repository. This is only required if the repository is set to private.
*/
accessToken?: string

/**
* A string representing a version of the Prismic repository's content. This may point to the latest version (called the "master ref"), or a preview with draft content.
*/
ref?: RefStringOrFn

/**
* Default parameters that will be sent with each query. These parameters can be overridden on each query if needed.
*/
defaultParams?: Omit<BuildQueryURLArgs, 'ref' | 'accessToken'>

/**
* The function used to make network requests to the Prismic REST API. In environments where a global `fetch` function does not exist, such as Node.js, this function must be provided.
*/
fetch?: Fetch
}

/**
* Parameters specific to client methods that fetch all documents. These methods start with `getAll` (for example, `getAllByType`).
*/
type GetAllParams = {
/**
* Limit the number of documents queried. If a number is not provided, there will be no limit and all matching documents will be returned.
*/
limit?: number
}

/**
* Arguments to determine how the URL for a preview session is resolved.
*/
type ResolvePreviewArgs = {
/**
* A function that maps a Prismic document to a URL within your app.
*/
linkResolver: LinkResolver

/**
* A fallback URL if the Link Resolver does not return a value.
*/
defaultUrl: string

/**
* The preview token (also known as a ref) that will be used to query preview content from the Prismic repository.
*/
previewToken?: string

/**
* The previewed document that will be used to determine the destination URL.
*/
documentId?: string
}

/**
* The largest page size allowed by the Prismic REST API V2. This value is used to minimize the number of requests required to query content.
*/
const MAX_PAGE_SIZE = 100

/**
* Creates a predicate to filter content by document type.
*
* @param documentType The document type to filter queried content.
*
* @returns A predicate that can be used in a Prismic REST API V2 request.
*/
const typePredicate = (documentType: string): string =>
predicate.at('document.type', documentType)

/**
* Creates a predicate to filter content by document tags.
*
* @param documentType Document tags to filter queried content.
*
* @returns A predicate that can be used in a Prismic REST API V2 request.
*/
const tagsPredicate = (tags: string | string[]): string =>
predicate.at('document.tags', tags)

/**
* Returns the first ref from a list that passes a predicate (a function that returns true).
*
* @throws If a matching ref cannot be found.
*
* @param refs A list of refs to search.
* @param predicate A function that determines if a ref from the list matches the criteria.
*
* @returns The first matching ref.
*/
const findRef = (refs: Ref[], predicate: (ref: Ref) => boolean): Ref => {
const ref = refs.find((ref) => predicate(ref))

Expand All @@ -55,10 +133,21 @@ const findRef = (refs: Ref[], predicate: (ref: Ref) => boolean): Ref => {
return ref
}

/**
* Creates a Prismic client that can be used to query a repository.
*
* @param endpoint The Prismic REST API V2 endpoint for the repository (use `prismic.getEndpoint` for the default endpoint).
* @param options Configuration that determines how content will be queried from the Prismic repository.
*
* @returns A client that can query content from the repository.
*/
export const createClient = (
...args: ConstructorParameters<typeof Client>
): Client => new Client(...args)

/**
* A client that allows querying content from a Prismic repository.
*/
export class Client {
endpoint: string
accessToken?: string
Expand All @@ -68,6 +157,14 @@ export class Client {
defaultParams?: Omit<BuildQueryURLArgs, 'ref'>
private autoPreviewsEnabled: boolean

/**
* Creates a Prismic client that can be used to query a repository.
*
* @param endpoint The Prismic REST API V2 endpoint for the repository (use `prismic.getEndpoint` to get the default endpoint).
* @param options Configuration that determines how content will be queried from the Prismic repository.
*
* @returns A client that can query content from the repository.
*/
constructor(endpoint: string, options: ClientConfig = {}) {
this.endpoint = endpoint
this.accessToken = options.accessToken
Expand Down Expand Up @@ -630,7 +727,7 @@ export class Client {
* @returns The preview ref as a string, if one exists.
*/
private getPreviewRefString(): string | undefined {
if (typeof globalThis.document !== 'undefined') {
if (globalThis.document?.cookie) {
return getCookie(cookie.preview, globalThis.document.cookie)
} else if (this.httpRequest?.headers?.cookie) {
return getCookie(cookie.preview, this.httpRequest.headers.cookie)
Expand Down
3 changes: 1 addition & 2 deletions src/cookie.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
/**
* The well-known name of the cookie used to store a Prismic preview session's
* ref.
* The well-known name of the cookie used to store a Prismic preview session's ref.
*/
export const preview = 'io.prismic.preview'
26 changes: 20 additions & 6 deletions src/lib/appendPredicates.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,23 @@ interface WithPredicates {
predicates?: string | string[]
}

export const appendPredicates = <T extends WithPredicates>(
...predicates: string[]
) => (params: T = {} as T): T => ({
...params,
predicates: [params.predicates || [], ...predicates].flat(),
})
/**
* Adds one or more predicates to an object with a `predicates` property. Appended predicates are added to the end of the existing list.
*
* @param predicates One or more predicates to append.
*
* @returns A function that accepts an object with a `predicates` property. The `predicates` list will be appended to that object.
*/
export const appendPredicates =
<T extends WithPredicates>(...predicates: string[]) =>
/**
* Adds one or more predicates to an object with a `predicates` property. Appended predicates are added to the end of the existing list.
*
* @param objWithPredicates Object to append predicates on the `predicates` property.
*
* @returns The object with the appended predicates.
*/
(objWithPredicates: T = {} as T): T => ({
...objWithPredicates,
predicates: [objWithPredicates.predicates || [], ...predicates].flat(),
})
7 changes: 7 additions & 0 deletions src/lib/castArray.ts
Original file line number Diff line number Diff line change
@@ -1 +1,8 @@
/**
* Ensures that a value is an array. If it is already an array, it is returned as is. If it is not an array, it is converted to an array with itself as its only element.
*
* @param a Value to ensure is an array.
*
* @returns `a` as an array.
*/
export const castArray = <A>(a: A | A[]): A[] => (Array.isArray(a) ? a : [a])
20 changes: 20 additions & 0 deletions src/lib/getCookie.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,15 @@
/**
* The following code is a modifed version of `es-cookie` taken from https://github.com/theodorejb/es-cookie
*
* Copyright 2017 Theodore Brown
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.*
*/

const readValue = (value: string): string => {
return value.replace(/%3B/g, ';')
}
Expand All @@ -19,6 +31,14 @@ export const parse = (cookieString: string): { [name: string]: string } => {
const getAll = (cookieStore: string): { [name: string]: string } =>
parse(cookieStore)

/**
* Returns the value of a cookie from a given cookie store.
*
* @param Name of the cookie.
* @param cookieStore The stringified cookie store from which to read the cookie.
*
* @returns The value of the cookie, if it exists.
*/
export const getCookie = (
name: string,
cookieStore: string,
Expand Down
10 changes: 10 additions & 0 deletions src/lib/orElseThrow.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,13 @@
/**
* Throws an error if a given value is nullish.
*
* @param a Nullable value to check.
* @param error Error to throw if `a` is nullish.
*
* @throws Throws the given error if `a` is nullish.
*
* @returns `a`, whose type is narrowed to be non-nullable.
*/
export const orElseThrow = <T>(a: T | null | undefined, error: Error): T => {
if (a == null) {
throw error
Expand Down

0 comments on commit 38052d2

Please sign in to comment.