Skip to content

Instantly share code, notes, and snippets.

@HendrikRoth
Forked from AlessioGr/PayloadCommunicator.ts
Last active December 11, 2023 15:45
Show Gist options
  • Save HendrikRoth/fe1000738f7e7bfbaef60af56d9fce61 to your computer and use it in GitHub Desktop.
Save HendrikRoth/fe1000738f7e7bfbaef60af56d9fce61 to your computer and use it in GitHub Desktop.
Simple helper you can use to communicate with Payload CMS from your application via their REST API. Authorization via API key needs to be enabled in your users collection. More on enabling API keys here: https://payloadcms.com/docs/authentication/config#api-keys
import { getDocumentByID } from "./PayloadCommunicator.ts";
import type { PageServerLoad } from './$types';
export const load = (async ({ params }) => {
return await getDocumentByID('collection', params.id);
}) satisfies PageServerLoad;
import qs from 'qs';
import { error } from '@sveltejs/kit';
export const cmsURL = "cms URL without the / at the end";
export const apiKey = "your api key";
export async function getDocuments (collectionName: string, whereQuery?) {
if (whereQuery) {
const stringifiedQuery = qs.stringify({
where: whereQuery
}, { addQueryPrefix: true });
const potentialFoundDocument = await (await fetch(`${cmsURL}/api/${collectionName}${stringifiedQuery}`, {
method: 'GET',
headers: {
"Content-Type": "application/json",
Authorization: `users API-Key ${apiKey}`
},
})).json()
if (potentialFoundDocument.errors) {
throw error(
404,
potentialFoundDocument.errors[0]
)
}
return potentialFoundDocument;
} else {
const potentialFoundDocument = await (await fetch(`${cmsURL}/api/${collectionName}`, {
method: 'GET',
headers: {
"Content-Type": "application/json",
Authorization: `users API-Key ${apiKey}`
},
})).json()
if (potentialFoundDocument.errors) {
throw error(
404,
potentialFoundDocument.errors[0]
)
}
return potentialFoundDocument;
}
}
export async function getDocumentByID (collectionName: string, id: string) {
const potentialFoundDocument = await (await fetch(`${cmsURL}/api/${collectionName}/${id}`, {
method: 'GET',
headers: {
"Content-Type": "application/json",
Authorization: `users API-Key ${apiKey}`
},
})).json()
if (potentialFoundDocument.errors) {
throw error(
404,
potentialFoundDocument.errors[0]
)
}
return potentialFoundDocument;
}
export async function newDocument (collectionName: string, initialFields) {
const requestResponse = await (await fetch(`${cmsURL}/api/${collectionName}`, {
method: 'POST',
headers: {
"Content-Type": "application/json",
Authorization: `users API-Key ${apiKey}`
},
body: JSON.stringify(initialFields),
})).json();
if (requestResponse.errors) {
throw error(
500,
requestResponse.errors[0]
)
}
return requestResponse;
}
export async function updateDocument (collectionName: string, documentToUpdateID: string, updatedFields) {
const requestResponse = await (await fetch(`${cmsURL}/api/${collectionName}/${documentToUpdateID}`, {
method: 'PATCH',
headers: {
"Content-Type": "application/json",
Authorization: `users API-Key ${apiKey}`
},
body: JSON.stringify(updatedFields),
})).json();
if (requestResponse.errors) {
throw error(
500,
requestResponse.errors[0]
)
}
return requestResponse;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment