Skip to content

Commit

Permalink
feat: add support for requestTagPrefix
Browse files Browse the repository at this point in the history
  • Loading branch information
stipsan committed Jun 28, 2023
1 parent b4f1323 commit 508639e
Show file tree
Hide file tree
Showing 7 changed files with 61 additions and 21 deletions.
8 changes: 4 additions & 4 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@sanity/groq-store",
"version": "2.2.2",
"version": "2.2.3-0",
"description": "Stream dataset to memory for in-memory querying",
"keywords": [
"sanity",
Expand Down
13 changes: 9 additions & 4 deletions src/browser/getDocuments.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,17 +10,22 @@ export const getDocuments: EnvImplementations['getDocuments'] = async function g
token,
documentLimit,
includeTypes = [],
requestTagPrefix,
}: {
projectId: string
dataset: string
token?: string
documentLimit?: number
includeTypes?: string[]
requestTagPrefix?: string
}): Promise<SanityDocument[]> {
const baseUrl = `https://${projectId}.api.sanity.io/v1/data/export/${dataset}`
const params =
includeTypes.length > 0 ? new URLSearchParams({types: includeTypes?.join(',')}) : ''
const url = `${baseUrl}?${params}`
const url = new URL(`https://${projectId}.api.sanity.io/v1/data/export/${dataset}`)
if (requestTagPrefix) {
url.searchParams.set('tag', requestTagPrefix)
}
if (includeTypes.length > 0) {
url.searchParams.set('types', includeTypes?.join(','))
}
const headers = token ? {Authorization: `Bearer ${token}`} : undefined
const response = await fetch(url, {credentials: 'include', headers})

Expand Down
20 changes: 15 additions & 5 deletions src/listen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,21 +43,24 @@ const addEventSourceListener = (
const encodeQueryString = ({
query,
params = {},
options = {effectFormat: 'mendoza'},
options = {},
}: {
query: string
params?: Record<string, unknown>
options?: Record<string, unknown>
}) => {
const searchParams = new URLSearchParams()
// We generally want tag at the start of the query string
const {tag, ...opts} = options
if (tag) searchParams.set('tag', tag as string)
searchParams.set('query', query)

// Iterate params, the keys are prefixed with `$` and their values JSON stringified
for (const [key, value] of Object.entries(params)) {
searchParams.set(`$${key}`, JSON.stringify(value))
}
// Options are passed as-is
for (const [key, value] of Object.entries(options)) {
for (const [key, value] of Object.entries(opts)) {
// Skip falsy values
if (value) searchParams.set(key, `${value}`)
}
Expand All @@ -74,14 +77,21 @@ export function listen(
next: (event: MutationEvent) => void
}
): Subscription {
const {projectId, dataset, token, includeTypes} = config
const {projectId, dataset, token, includeTypes, requestTagPrefix} = config
const headers = token ? {Authorization: `Bearer ${token}`} : undefined

// Make sure we only listen to mutations on documents part of the `includeTypes` allowlist, if provided
const options = requestTagPrefix
? {tag: requestTagPrefix, effectFormat: 'mendoza'}
: {effectFormat: 'mendoza'}
const searchParams = encodeQueryString(
Array.isArray(includeTypes) && includeTypes.length > 0
? {query: `*[_type in $includeTypes]`, params: {includeTypes}}
: {query: '*'}
? {
query: `*[_type in $includeTypes]`,
params: {includeTypes},
options,
}
: {query: '*', options}
)
const url = `https://${projectId}.api.sanity.io/v1/data/listen/${dataset}${searchParams}`
const es = new EventSourceImpl(url, {withCredentials: true, headers})
Expand Down
14 changes: 10 additions & 4 deletions src/node/getDocuments.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,17 +10,23 @@ export const getDocuments: EnvImplementations['getDocuments'] = function getDocu
token,
documentLimit,
includeTypes = [],
requestTagPrefix,
}: {
projectId: string
dataset: string
token?: string
documentLimit?: number
includeTypes?: string[]
requestTagPrefix?: string
}): Promise<SanityDocument[]> {
const baseUrl = `https://${projectId}.api.sanity.io/v1/data/export/${dataset}`
const params =
includeTypes.length > 0 ? new URLSearchParams({types: includeTypes?.join(',')}) : ''
const url = `${baseUrl}?${params}`
const baseUrl = new URL(`https://${projectId}.api.sanity.io/v1/data/export/${dataset}`)
if (requestTagPrefix) {
baseUrl.searchParams.set('tag', requestTagPrefix)
}
if (includeTypes.length > 0) {
baseUrl.searchParams.set('types', includeTypes?.join(','))
}
const url = baseUrl.toString()
const headers = token ? {Authorization: `Bearer ${token}`} : undefined

return new Promise((resolve, reject) => {
Expand Down
19 changes: 17 additions & 2 deletions src/syncingDataset.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ export function getSyncingDataset(
documentLimit,
token,
includeTypes,
requestTagPrefix,
} = config

// We don't want to flush updates while we're in the same transaction, so a normal
Expand All @@ -44,7 +45,14 @@ export function getSyncingDataset(
}

if (!useListener) {
const loaded = getDocuments({projectId, dataset, documentLimit, token, includeTypes})
const loaded = getDocuments({
projectId,
dataset,
documentLimit,
token,
includeTypes,
requestTagPrefix,
})
.then(onUpdate)
.then(noop)
return {unsubscribe: noop, loaded}
Expand All @@ -67,7 +75,14 @@ export function getSyncingDataset(
})

const onOpen = async () => {
const initial = await getDocuments({projectId, dataset, documentLimit, token, includeTypes})
const initial = await getDocuments({
projectId,
dataset,
documentLimit,
token,
includeTypes,
requestTagPrefix,
})
documents = applyBufferedMutations(initial, buffer)
documents.forEach((doc) => indexedDocuments.set(doc._id, doc))
onUpdate(documents)
Expand Down
6 changes: 5 additions & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,10 @@ export interface GroqSubscription {
export interface EnvImplementations {
EventSource: typeof NodeEventSource | typeof BrowserEventSource | typeof window.EventSource
getDocuments: (
options: Pick<Config, 'projectId' | 'dataset' | 'token' | 'documentLimit' | 'includeTypes'>
options: Pick<
Config,
'projectId' | 'dataset' | 'token' | 'documentLimit' | 'includeTypes' | 'requestTagPrefix'
>
) => Promise<SanityDocument[]>
}

Expand Down Expand Up @@ -77,6 +80,7 @@ export interface Config {
* @example ['page', 'product', 'sanity.imageAsset']
*/
includeTypes?: string[]
requestTagPrefix?: string
}

/** @public */
Expand Down

0 comments on commit 508639e

Please sign in to comment.