@nuxtjs/sanity
Version:
Sanity integration for Nuxt
66 lines (65 loc) • 2.01 kB
JavaScript
import { $fetch } from "ofetch";
const apiHost = "api.sanity.io";
const cdnHost = "apicdn.sanity.io";
const enc = encodeURIComponent;
export function getQuery(query, params = {}) {
const baseQs = `?query=${enc(query)}`;
return Object.keys(params).reduce((current, param) => {
return `${current}&${enc(`$${param}`)}=${enc(
JSON.stringify(params[param])
)}`;
}, baseQs);
}
export const getByteSize = (query) => encodeURI(query).split(/%..|./).length;
export function createClient(config) {
const {
projectId,
dataset,
apiVersion = "1",
withCredentials,
token,
perspective = "raw"
} = config;
const useCdn = perspective !== "previewDrafts" && config.useCdn;
const fetchOptions = {
headers: {
...token ? { Authorization: `Bearer ${token}` } : {},
Accept: "application/json",
...import.meta.server ? { "accept-encoding": "gzip, deflate" } : {}
}
};
if (import.meta.client) {
fetchOptions.credentials = withCredentials ? "include" : "omit";
}
const clientConfig = {
useCdn,
projectId,
dataset,
apiVersion,
withCredentials,
token,
perspective
};
async function fetch(query, params, options) {
const requestPerspective = options?.perspective || perspective;
const qs = getQuery(query, params) + `&perspective=${requestPerspective}`;
const usePostRequest = getByteSize(qs) > 9e3;
const host = useCdn && !usePostRequest ? cdnHost : apiHost;
const urlBase = `https://${projectId}.${host}/v${apiVersion}/data/query/${dataset}`;
const response = usePostRequest ? await $fetch(urlBase, {
...fetchOptions,
method: "post",
body: { query, params },
query: { perspective: requestPerspective }
}) : await $fetch(`${urlBase}${qs}`, fetchOptions);
if (options?.filterResponse === false) {
return response;
}
return response.result;
}
return {
config: () => clientConfig,
clone: () => createClient(clientConfig),
fetch
};
}