Skip to content

Commit 988b71a

Browse files
committed
initial version
1 parent d37ab42 commit 988b71a

11 files changed

Lines changed: 654 additions & 77 deletions

File tree

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,3 @@
11
node_modules
22
dist
3+
bun.lockb

LICENSE

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
MIT License
22

3-
Copyright (c) 2022 Robert Soriano <https://github.com/wobsoriano>
3+
Copyright (c) 2025 Kfir Matityahu
44

55
Permission is hereby granted, free of charge, to any person obtaining a copy
66
of this software and associated documentation files (the "Software"), to deal
@@ -18,4 +18,4 @@ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
1818
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
1919
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
2020
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21-
SOFTWARE.
21+
SOFTWARE.

README.md

Lines changed: 122 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,135 @@
1-
# bun starter
1+
# Payload Express Middleware
22

3-
## Getting Started
3+
`payload-express-middleware` is a library that enables API routing in Express.js, similar to Next.js API routes, using [Payload CMS](https://payloadcms.com). This middleware simplifies the process of integrating Payload's Local API with an Express.js application.
44

5-
Click the [Use this template](https://github.com/wobsoriano/bun-lib-starter/generate) button to create a new repository with the contents starter.
5+
## Features
66

7-
OR
7+
- Seamlessly map API routes to Payload CMS collections.
8+
- Built-in authentication and authorization middleware.
9+
- CRUD operations for Payload collections.
10+
- Error handling for common Payload validation and authentication errors.
811

9-
Run `bun create wobsoriano/bun-lib-starter ./my-lib`.
12+
## Installation
1013

11-
## Setup
14+
Install the library and its peer dependencies:
1215

16+
NPM
1317
```bash
14-
# install dependencies
15-
bun install
18+
npm install payload-express-middleware payload express
19+
```
20+
21+
Yarn
22+
```bash
23+
yarn add payload-express-middleware payload express
24+
```
25+
26+
## Usage
27+
28+
### 1. Initialize Payload CMS
29+
30+
Ensure you have a Payload CMS configuration file (e.g., `payload.config.js`) and initialize Payload in your Express app.
31+
32+
### 2. Use the Middleware
33+
34+
Import and use the `payloadAPIRouterMiddleware` function in your Express app:
35+
36+
```typescript
37+
import express from 'express';
38+
import payload from 'payload';
39+
import { payloadAPIRouterMiddleware } from 'payload-express-middleware';
40+
import path from 'path';
41+
42+
const app = express();
43+
44+
async function start() {
45+
// Load Payload configuration
46+
const config = path.resolve(__dirname, '/route/to/payload.config.js');
47+
48+
// Initialize Payload
49+
await payload.init({
50+
secret: 'PAYLOAD_SECRET', // Replace with your Payload secret
51+
config,
52+
});
53+
54+
// Use the middleware
55+
app.use(payloadAPIRouterMiddleware(payload));
56+
57+
// Use your other middleware, routes, etc
58+
// ....
59+
60+
// Start the server
61+
app.listen(4000, () => {
62+
console.log('Express API running on port 4000');
63+
});
64+
}
1665

17-
# test the app
18-
bun test
66+
start();
67+
```
68+
69+
### 3. API Routes
70+
71+
The middleware automatically maps the following routes to Payload's Local API:
72+
73+
#### Authentication Routes
74+
- **Login**: `POST /api/users-collection}/login`
75+
- **Logout**: `POST /api/{users-collection}/logout`
76+
- **Me**: `GET /api/{users-collection}/me`
77+
78+
Note: `{user-collection}` defined by your `payload.config.js`
79+
80+
#### CRUD Routes
81+
82+
- **Find Many**: `GET /api/:collection`
83+
- **Find By ID**: `GET /api/:collection/:id`
84+
- **Create**: `POST /api/:collection`
85+
- **Update**: `PATCH /api/:collection/:id`
86+
- **Delete**: `DELETE /api/:collection/:id`
87+
88+
### 4. Example Payload Configuration
1989

20-
# build the app, available under dist
21-
bun run build
90+
Ensure your Payload CMS configuration file (`payload.config.js`) is properly set up. For example:
91+
92+
```javascript
93+
module.exports = {
94+
secret: 'MY_SECRET',
95+
collections: [
96+
{
97+
slug: 'users',
98+
admin: true, // --> enables 'user-collection' for Auth operations
99+
fields: [
100+
{ name: 'email', type: 'email', required: true },
101+
{ name: 'password', type: 'password', required: true },
102+
],
103+
},
104+
{
105+
slug: 'posts',
106+
fields: [
107+
{ name: 'title', type: 'text', required: true },
108+
{ name: 'content', type: 'richText' },
109+
],
110+
},
111+
],
112+
};
22113
```
23114

115+
## API Documentation
116+
117+
### `payloadAPIRouterMiddleware(payload: Payload)`
118+
119+
This function creates an Express router that maps API routes to Payload's Local API.
120+
121+
#### Parameters
122+
- `payload`: The initialized Payload CMS instance.
123+
124+
125+
## Error Handling
126+
127+
The middleware includes built-in error handling for:
128+
- Validation errors (`400 Bad Request`).
129+
- Authentication errors (`401 Unauthorized`).
130+
- Not found errors (`404 Not Found`).
131+
- Generic server errors (`500 Internal Server Error`).
132+
24133
## License
25134

26-
MIT
135+
This project is licensed under the [MIT License](LICENSE).

build.ts

Lines changed: 80 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,80 @@
1-
import type { BuildConfig } from 'bun'
2-
import dts from 'bun-plugin-dts'
3-
4-
const defaultBuildConfig: BuildConfig = {
5-
entrypoints: ['./src/index.ts'],
6-
outdir: './dist'
7-
}
8-
9-
await Promise.all([
10-
Bun.build({
11-
...defaultBuildConfig,
12-
plugins: [dts()],
13-
format: 'esm',
14-
naming: "[dir]/[name].js",
15-
}),
16-
Bun.build({
17-
...defaultBuildConfig,
18-
format: 'cjs',
19-
naming: "[dir]/[name].cjs",
20-
})
21-
])
1+
// // import { Glob, $ } from "bun"
2+
3+
// // await $`rm -rf dist`
4+
// // const files = new Glob("./src/**/*.{ts,tsx}").scan()
5+
// // for await (const file of files) {
6+
// // await Bun.build({
7+
// // format: "esm",
8+
// // outdir: "dist/esm",
9+
// // external: ["*"],
10+
// // root: "src",
11+
// // entrypoints: [file],
12+
// // })
13+
// // }
14+
// // await $`tsc --outDir dist/types --declaration --emitDeclarationOnly --declarationMap`
15+
16+
17+
18+
// import type { BuildConfig } from 'bun'
19+
// import dts from 'bun-plugin-dts'
20+
21+
// const defaultBuildConfig: BuildConfig = {
22+
// entrypoints: ['src/index.ts'],
23+
// outdir: 'dist',
24+
// target: 'node',
25+
// }
26+
27+
// await Promise.all([
28+
// Bun.build({
29+
// ...defaultBuildConfig,
30+
// plugins: [dts()],
31+
// format: 'esm',
32+
// naming: "[dir]/[name].js",
33+
// }),
34+
35+
// Bun.build({
36+
// ...defaultBuildConfig,
37+
// //@ts-ignore
38+
// format: 'cjs',
39+
// naming: "[dir]/[name].cjs",
40+
// })
41+
// ])
42+
43+
44+
45+
// await Bun.build({
46+
// entrypoints: ["src/index.ts"],
47+
// outdir: "dist",
48+
// format: "esm",
49+
// target: "node",
50+
// plugins: [dts()],
51+
// external: ["*"], // do not bundle dependencies
52+
// splitting: false,
53+
// });
54+
55+
// const files = new Glob("./src/**/*.{ts,tsx}").scan()
56+
// for await (const file of files) {
57+
// await Bun.build({
58+
// format: "esm",
59+
// outdir: "dist",
60+
// external: ["*"],
61+
// root: "src",
62+
// entrypoints: [file],
63+
// plugins: [dts()],
64+
// })
65+
// }
66+
67+
// import dts from 'bun-plugin-dts';
68+
import { $ } from "bun"
69+
70+
await $`rm -rf dist`
71+
72+
await Bun.build({
73+
entrypoints: ["src/index.ts"],
74+
outdir: "dist/esm",
75+
format: "esm",
76+
external: ["*"],
77+
// plugins: [dts()],
78+
})
79+
80+
await $`tsc --outDir dist/types --declaration --emitDeclarationOnly --declarationMap`

bun.lockb

93.7 KB
Binary file not shown.

bunfig.toml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
[install]
2+
exact = true

package.json

Lines changed: 39 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,36 +1,58 @@
11
{
22
"name": "payload-express-middleware",
3+
"version": "0.3.0",
4+
"author": "Kfir Matityhau<kfir25812@gmail.com>",
5+
"homepage:": "https://github.com/kfiross/payload-express-middleware",
6+
"description": "Enabling Express.js backend to interact with Payload CMS APIs seemlessly",
7+
"license": "MIT",
38
"type": "module",
4-
"version": "0.0.0",
5-
"main": "./dist/index.cjs",
6-
"module": "./dist/index.js",
7-
"types": "./dist/index.d.ts",
8-
"description": "",
9-
"exports": {
10-
"types": "./dist/index.d.ts",
11-
"import": "./dist/index.js",
12-
"require": "./dist/index.cjs"
13-
},
9+
"main": "./dist/esm/index.js",
10+
"module": "./dist/esm/index.js",
11+
"types": "./dist/types/index.d.ts",
12+
"exports": {
13+
".": {
14+
"import": "./dist/esm/index.js",
15+
"require": "./dist/esm/index.js",
16+
"types": "./dist/types/index.d.ts"
17+
}
18+
},
1419
"scripts": {
1520
"build": "bun run build.ts",
16-
"prepublishOnly": "bun run build"
21+
"format": "bun x prettier --write '**/*.{js,jsx,ts,tsx,json,md,yaml,yml}'",
22+
"release": "bun run build && changeset publish"
1723
},
1824
"files": [
25+
"src",
1926
"dist"
2027
],
2128
"keywords": [
29+
"payload",
30+
"express",
31+
"middleware",
2232
"bun"
2333
],
24-
"license": "MIT",
25-
"homepage": "https://github.com/wobsoriano/pkg-name#readme",
34+
"homepage": "https://github.com/kfiross/payload-express-middleware#readme",
2635
"repository": {
2736
"type": "git",
28-
"url": "git+https://github.com/wobsoriano/pkg-name.git"
37+
"url": "git+https://github.com/kfiross/payload-express-middleware.git"
38+
},
39+
"bugs": {
40+
"url": "https://github.com/kfiross/payload-express-middleware/issues"
41+
},
42+
"dependencies": {
43+
"express": "^4.18.2",
44+
"payload": "^3.0.0",
45+
"jsonwebtoken": "^9.0.0"
2946
},
30-
"bugs": "https://github.com/wobsoriano/pkg-name/issues",
31-
"author": "Robert Soriano <sorianorobertc@gmail.com>",
3247
"devDependencies": {
48+
"@types/bun": "^1.1.10",
49+
"@types/express": "4.17.21",
50+
"@types/jest": "29.5.12",
51+
"@types/jsonwebtoken": "9.0.10",
52+
"@types/node": "^22.13.13",
3353
"bun-plugin-dts": "^0.3.0",
34-
"@types/bun": "^1.1.10"
54+
"prettier": "3.6.2",
55+
"sort-package-json": "3.4.0",
56+
"typescript": "5.9.3"
3557
}
3658
}

script/changelog.sh

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
#!/usr/bin/env bash
2+
3+
# Get the package version from package.json
4+
PACKAGE_VERSION=$(node -p -e "require('./package.json').version || ''")
5+
6+
# Check if PACKAGE_VERSION is empty
7+
if [ -z "$PACKAGE_VERSION" ]; then
8+
echo "Error: Failed to retrieve version from package.json"
9+
exit 1
10+
fi
11+
12+
# Run git-cliff with the correct tag
13+
bun x git-cliff -o './CHANGELOG.md' --tag "$PACKAGE_VERSION"

0 commit comments

Comments
 (0)