-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathload-query.ts
42 lines (37 loc) · 1.05 KB
/
load-query.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// load-query.ts
import { type QueryParams } from 'sanity';
import { sanityClient } from 'sanity:client';
const visualEditingEnabled =
import.meta.env.PUBLIC_SANITY_VISUAL_EDITING_ENABLED === 'true';
const token = import.meta.env.SANITY_API_READ_TOKEN;
export async function loadQuery<QueryResponse>({
query,
params,
}: {
query: string;
params?: QueryParams;
}) {
if (visualEditingEnabled && !token) {
throw new Error(
'The `SANITY_API_READ_TOKEN` environment variable is required during Visual Editing.'
);
}
const perspective = visualEditingEnabled ? 'previewDrafts' : 'published';
const { result, resultSourceMap } = await sanityClient.fetch<QueryResponse>(
query,
params ?? {},
{
filterResponse: false,
perspective,
resultSourceMap: visualEditingEnabled ? 'withKeyArraySelector' : false,
stega: visualEditingEnabled,
...(visualEditingEnabled ? { token } : {}),
useCdn: !visualEditingEnabled,
}
);
return {
data: result,
sourceMap: resultSourceMap,
perspective,
};
}