Skip to content

Commit

Permalink
feat: add Payload SDK package
Browse files Browse the repository at this point in the history
  • Loading branch information
r1tsuu committed Dec 2, 2024
1 parent 58b7415 commit 86da15a
Show file tree
Hide file tree
Showing 45 changed files with 2,342 additions and 4 deletions.
1 change: 1 addition & 0 deletions .github/workflows/pr-title.yml
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ jobs:
richtext-\*
richtext-lexical
richtext-slate
sdk
storage-\*
storage-azure
storage-gcs
Expand Down
213 changes: 213 additions & 0 deletions docs/rest-api/overview.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ keywords: rest, api, documentation, Content Management System, cms, headless, ja
The REST API is a fully functional HTTP client that allows you to interact with your Documents in a RESTful manner. It supports all CRUD operations and is equipped with automatic pagination, depth, and sorting.
All Payload API routes are mounted and prefixed to your config's `routes.api` URL segment (default: `/api`).

To enhance DX, you can use [Payload SDK](#payload-rest-api-sdk) to query your REST API.

**REST query parameters:**

- [depth](../queries/depth) - automatically populates relationships and uploads
Expand Down Expand Up @@ -752,3 +754,214 @@ const res = await fetch(`${api}/${collectionSlug}?depth=1&locale=en`, {
},
})
```

## Payload REST API SDK

The best, fully type-safe way to query Payload REST API is to use its SDK client, which can be installed with:

```bash
pnpm add @payloadcms/sdk
```

Its usage is very similar to [the Local API](../local-api/overview).

Example:
```ts
import { PayloadSDK } from '@payloadcms/sdk'
import type { Config } from './payload-types'

// Pass your config from generated types as generic
const sdk = new PayloadSDK<Config>({
baseURL: 'https://example.com/api',
})

// Find operation
const posts = await sdk.find({
collection: 'posts',
draft: true,
limit: 10,
locale: 'en',
page: 1,
where: { _status: { equals: 'published' } },
})

// Find by ID operation
const posts = await sdk.findByID({
id,
collection: 'posts',
draft: true,
locale: 'en',
})

// Auth login operation
const result = await sdk.login({
collection: 'users',
data: {
email: '[email protected]',
password: '12345',
},
})

// Create operation
const result = await sdk.create({
collection: 'posts',
data: { text: 'text' },
})

// Create operation with a file
// `file` can be either a Blob | File object or a string URL
const result = await sdk.create({ collection: 'media', file, data: {} })

// Count operation
const result = await sdk.count({ collection: 'posts', where: { id: { equals: post.id } } })

// Update (by ID) operation
const result = await sdk.update({
collection: 'posts',
id: post.id,
data: {
text: 'updated-text',
},
})

// Update (bulk) operation
const result = await sdk.update({
collection: 'posts',
where: {
id: {
equals: post.id,
},
},
data: { text: 'updated-text-bulk' },
})

// Delete (by ID) operation
const result = await sdk.delete({ id: post.id, collection: 'posts' })

// Delete (bulk) operation
const result = await sdk.delete({ where: { id: { equals: post.id } }, collection: 'posts' })

// Find Global operation
const result = await sdk.findGlobal({ slug: 'global' })

// Update Global operation
const result = await sdk.updateGlobal({ slug: 'global', data: { text: 'some-updated-global' } })

// Auth Login operation
const result = await sdk.login({
collection: 'users',
data: { email: '[email protected]', password: '123456' },
})

// Auth Me operation
const result = await sdk.me(
{ collection: 'users' },
{
headers: {
Authorization: `JWT ${user.token}`,
},
},
)

// Auth Refresh Token operation
const result = await sdk.refreshToken(
{ collection: 'users' },
{ headers: { Authorization: `JWT ${user.token}` } },
)

// Auth Forgot Password operation
const result = await sdk.forgotPassword({
collection: 'users',
data: { email: user.email },
})

// Auth Reset Password operation
const result = await sdk.resetPassword({
collection: 'users',
data: { password: '1234567', token: resetPasswordToken },
})
```



Every operation has optional 3rd parameter which is used to add additional data to the RequestInit object (like headers):
```ts
await sdk.me({
collection: "users"
}, {
// RequestInit object
headers: {
Authorization: `JWT ${token}`
}
})
```

To query custom endpoints, you can use the `request` method, which is used internally for all other methods:
```ts
await sdk.request({
method: 'POST',
path: '/send-data',
json: {
id: 1,
},
})
```

Custom `fetch` implementation and `baseInit` for shared `RequestInit` properties:
```ts
const sdk = new PayloadSDK<Config>({
baseInit: { credentials: 'include' },
baseURL: 'https://example.com/api',
fetch: async (url, init) => {
console.log('before req')
const response = await fetch(url, init)
console.log('after req')
return response
},
})
```

Example of a custom `fetch` implementation for testing the REST API without needing to spin up a next development server:
```ts
import type { GeneratedTypes, SanitizedConfig } from 'payload'

import config from '@payload-config'
import { REST_DELETE, REST_GET, REST_PATCH, REST_POST, REST_PUT } from '@payloadcms/next/routes'
import { PayloadSDK } from '@payloadcms/sdk'

export type TypedPayloadSDK = PayloadSDK<GeneratedTypes>

const api = {
GET: REST_GET(config),
POST: REST_POST(config),
PATCH: REST_PATCH(config),
DELETE: REST_DELETE(config),
PUT: REST_PUT(config),
}

const awaitedConfig = await config

export const sdk = new PayloadSDK<GeneratedTypes>({
baseURL: ``,
fetch: (path: string, init: RequestInit) => {
const [slugs, search] = path.slice(1).split('?')
const url = `${awaitedConfig.serverURL || 'http://localhost:3000'}${awaitedConfig.routes.api}/${slugs}${search ? `?${search}` : ''}`

if (init.body instanceof FormData) {
const file = init.body.get('file') as Blob
if (file && init.headers instanceof Headers) {
init.headers.set('Content-Length', file.size.toString())
}
}
const request = new Request(url, init)

const params = {
params: Promise.resolve({
slug: slugs.split('/'),
}),
}

return api[init.method.toUpperCase()](request, params)
},
})
```
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
"build:plugins": "turbo build --filter \"@payloadcms/plugin-*\"",
"build:richtext-lexical": "turbo build --filter \"@payloadcms/richtext-lexical\"",
"build:richtext-slate": "turbo build --filter \"@payloadcms/richtext-slate\"",
"build:sdk": "turbo build --filter \"@payloadcms/sdk\"",
"build:storage-azure": "turbo build --filter \"@payloadcms/storage-azure\"",
"build:storage-gcs": "turbo build --filter \"@payloadcms/storage-gcs\"",
"build:storage-s3": "turbo build --filter \"@payloadcms/storage-s3\"",
Expand Down
10 changes: 10 additions & 0 deletions packages/sdk/.prettierignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
.tmp
**/.git
**/.hg
**/.pnp.*
**/.svn
**/.yarn/**
**/build
**/dist/**
**/node_modules
**/temp
24 changes: 24 additions & 0 deletions packages/sdk/.swcrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
{
"$schema": "https://json.schemastore.org/swcrc",
"sourceMaps": true,
"jsc": {
"target": "esnext",
"parser": {
"syntax": "typescript",
"tsx": true,
"dts": true
},
"transform": {
"react": {
"runtime": "automatic",
"pragmaFrag": "React.Fragment",
"throwIfNamespace": true,
"development": false,
"useBuiltins": true
}
}
},
"module": {
"type": "es6"
}
}
18 changes: 18 additions & 0 deletions packages/sdk/eslint.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { rootEslintConfig, rootParserOptions } from '../../eslint.config.js'

/** @typedef {import('eslint').Linter.Config} Config */

/** @type {Config[]} */
export const index = [
...rootEslintConfig,
{
languageOptions: {
parserOptions: {
...rootParserOptions,
tsconfigRootDir: import.meta.dirname,
},
},
},
]

export default index
22 changes: 22 additions & 0 deletions packages/sdk/license.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
MIT License

Copyright (c) 2018-2024 Payload CMS, Inc. <[email protected]>

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.
63 changes: 63 additions & 0 deletions packages/sdk/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
{
"name": "@payloadcms/sdk",
"version": "3.1.0",
"description": "The official Payload REST API SDK",
"homepage": "https://payloadcms.com",
"repository": {
"type": "git",
"url": "https://github.com/payloadcms/payload.git",
"directory": "packages/sdk"
},
"license": "MIT",
"author": "Payload <[email protected]> (https://payloadcms.com)",
"maintainers": [
{
"name": "Payload",
"email": "[email protected]",
"url": "https://payloadcms.com"
}
],
"type": "module",
"exports": {
".": {
"import": "./src/index.ts",
"types": "./src/index.ts",
"default": "./src/index.ts"
}
},
"main": "./src/index.ts",
"types": "./src/index.ts",
"files": [
"dist"
],
"scripts": {
"build": "pnpm copyfiles && pnpm build:types && pnpm build:swc",
"build:swc": "swc ./src -d ./dist --config-file .swcrc --strip-leading-paths",
"build:types": "tsc --emitDeclarationOnly --outDir dist",
"clean": "rimraf {dist,*.tsbuildinfo}",
"copyfiles": "copyfiles -u 1 \"src/**/*.{html,css,scss,ttf,woff,woff2,eot,svg,jpg,png,json}\" dist/",
"lint": "eslint .",
"lint:fix": "eslint . --fix",
"prepublishOnly": "pnpm clean && pnpm turbo build"
},
"dependencies": {
"payload": "workspace:*",
"qs-esm": "7.0.2",
"ts-essentials": "10.0.3"
},
"devDependencies": {
"@payloadcms/eslint-config": "workspace:*"
},
"publishConfig": {
"exports": {
".": {
"import": "./dist/index.js",
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
}
},
"main": "./dist/index.js",
"registry": "https://registry.npmjs.org/",
"types": "./dist/index.d.ts"
}
}
Loading

0 comments on commit 86da15a

Please sign in to comment.