chore: adds rest client for Next handlers

This commit is contained in:
Jarrod Flesch
2024-02-15 10:01:13 -05:00
parent 6fa72cf912
commit db6758f7f7
13 changed files with 300 additions and 330 deletions

View File

@@ -1,20 +1,15 @@
import type { Payload } from '../../packages/payload/src'
import { GET as createGET, POST as createPOST } from '../../packages/next/src/routes/rest/index'
import { getPayload } from '../../packages/payload/src'
import { devUser } from '../credentials'
import { NextRESTClient } from '../helpers/NextRESTClient'
import { postsSlug } from './collections/Posts'
import config from './config'
import configPromise from './config'
let payload: Payload
let jwt
let token: string
let restClient: NextRESTClient
const GET = createGET(config)
const POST = createPOST(config)
const headers = {
'Content-Type': 'application/json',
}
const { email, password } = devUser
describe('_Community Tests', () => {
@@ -22,28 +17,19 @@ describe('_Community Tests', () => {
// Boilerplate test setup/teardown
// --__--__--__--__--__--__--__--__--__
beforeAll(async () => {
payload = await getPayload({ config })
payload = await getPayload({ config: configPromise })
restClient = new NextRESTClient(payload.config)
const req = new Request('http://localhost:3000/api/users/login', {
method: 'POST',
headers: new Headers(headers),
body: JSON.stringify({
email,
password,
}),
})
const data = await restClient
.POST('/users/login', {
body: JSON.stringify({
email,
password,
}),
})
.then((res) => res.json())
const data = await POST(req, {
params: {
slug: ['users', 'login'],
},
}).then((res) => res.json())
jwt = data.token
})
beforeEach(() => {
jest.resetModules()
token = data.token
})
afterAll(async () => {
@@ -69,22 +55,16 @@ describe('_Community Tests', () => {
})
it('rest API example', async () => {
const req = new Request(`http://localhost:3000/posts`, {
method: 'POST',
headers: new Headers({
...headers,
Authorization: `JWT ${jwt}`,
}),
body: JSON.stringify({
text: 'REST API EXAMPLE',
}),
})
const data = await POST(req, {
params: {
slug: ['posts'],
},
}).then((res) => res.json())
const data = await restClient
.POST(`/${postsSlug}`, {
body: JSON.stringify({
text: 'REST API EXAMPLE',
}),
headers: {
Authorization: `JWT ${token}`,
},
})
.then((res) => res.json())
expect(data.doc.text).toEqual('REST API EXAMPLE')
})

View File

@@ -158,16 +158,16 @@ export default buildConfigWithDefaults({
label: 'Custom',
type: 'text',
},
{
name: 'authDebug',
label: 'Auth Debug',
type: 'ui',
admin: {
components: {
Field: AuthDebug,
},
},
},
// {
// name: 'authDebug',
// label: 'Auth Debug',
// type: 'ui',
// admin: {
// components: {
// Field: AuthDebug,
// },
// },
// },
],
},
{

View File

@@ -1,37 +1,24 @@
import { GraphQLClient } from 'graphql-request'
import jwtDecode from 'jwt-decode'
import type { Payload } from '../../packages/payload/src'
import type { User } from '../../packages/payload/src/auth'
import configPromise from '../collections-graphql/config'
import { getPayload } from '../../packages/payload/src'
import { devUser } from '../credentials'
import { initPayloadTest } from '../helpers/configHelpers'
import { NextRESTClient } from '../helpers/NextRESTClient'
import configPromise from './config'
import { namedSaveToJWTValue, saveToJWTKey, slug } from './shared'
require('isomorphic-fetch')
let apiUrl
let client: GraphQLClient
let restClient: NextRESTClient
let payload: Payload
const headers = {
'Content-Type': 'application/json',
}
const { email, password } = devUser
describe('Auth', () => {
beforeAll(async () => {
const { serverURL, payload: payloadClient } = await initPayloadTest({
__dirname,
init: { local: false },
})
payload = payloadClient
apiUrl = `${serverURL}/api`
const config = await configPromise
const url = `${serverURL}${config.routes.api}${config.routes.graphQL}`
client = new GraphQLClient(url)
payload = await getPayload({ config: configPromise, disableOnInit: true })
restClient = new NextRESTClient(payload.config)
})
afterAll(async () => {
@@ -40,27 +27,28 @@ describe('Auth', () => {
}
})
beforeEach(() => {
jest.resetModules()
})
describe('GraphQL - admin user', () => {
let token
let user
beforeAll(async () => {
// language=graphQL
const query = `mutation {
loginUser(email: "${devUser.email}", password: "${devUser.password}") {
const { data } = await restClient
.GRAPHQL_POST({
body: JSON.stringify({
query: `mutation {
loginUser(email: "${devUser.email}", password: "${devUser.password}") {
token
user {
id
email
}
}
}`
const response = await client.request(query)
user = response.loginUser.user
token = response.loginUser.token
}
}`,
}),
})
.then((res) => res.json())
user = data.loginUser.user
token = data.loginUser.token
})
it('should login', async () => {
@@ -83,37 +71,32 @@ describe('Auth', () => {
describe('REST - admin user', () => {
beforeAll(async () => {
await fetch(`${apiUrl}/${slug}/first-register`, {
const u = await restClient.POST(`/${slug}/first-register`, {
body: JSON.stringify({
email,
password,
}),
headers,
method: 'post',
})
const t = u
})
it('should prevent registering a new first user', async () => {
const response = await fetch(`${apiUrl}/${slug}/first-register`, {
const response = await restClient.POST(`/${slug}/first-register`, {
body: JSON.stringify({
email: 'thisuser@shouldbeprevented.com',
password: 'get-out',
email,
password,
}),
headers,
method: 'post',
})
expect(response.status).toBe(403)
})
it('should login a user successfully', async () => {
const response = await fetch(`${apiUrl}/${slug}/login`, {
const response = await restClient.POST(`/${slug}/login`, {
body: JSON.stringify({
email,
password,
}),
headers,
method: 'post',
})
const data = await response.json()
@@ -127,13 +110,11 @@ describe('Auth', () => {
let loggedInUser: User | undefined
beforeAll(async () => {
const response = await fetch(`${apiUrl}/${slug}/login`, {
const response = await restClient.POST(`/${slug}/login`, {
body: JSON.stringify({
email,
password,
}),
headers,
method: 'post',
})
const data = await response.json()
@@ -155,9 +136,8 @@ describe('Auth', () => {
})
it('should return a logged in user from /me', async () => {
const response = await fetch(`${apiUrl}/${slug}/me`, {
const response = await restClient.GET(`/${slug}/me`, {
headers: {
...headers,
Authorization: `JWT ${token}`,
},
})
@@ -218,9 +198,8 @@ describe('Auth', () => {
},
})
const response = await fetch(`${apiUrl}/${slug}/me`, {
const response = await restClient.GET(`/${slug}/me`, {
headers: {
...headers,
Authorization: `${slug} API-Key ${user?.apiKey}`,
},
})
@@ -233,11 +212,10 @@ describe('Auth', () => {
})
it('should refresh a token and reset its expiration', async () => {
const response = await fetch(`${apiUrl}/${slug}/refresh-token`, {
const response = await restClient.POST(`/${slug}/refresh-token`, {
headers: {
Authorization: `JWT ${token}`,
},
method: 'post',
})
const data = await response.json()
@@ -257,11 +235,10 @@ describe('Auth', () => {
},
})
const response = await fetch(`${apiUrl}/${slug}/refresh-token`, {
const response = await restClient.POST(`/${slug}/refresh-token`, {
headers: {
Authorization: `JWT ${token}`,
},
method: 'post',
})
const data = await response.json()
@@ -271,7 +248,7 @@ describe('Auth', () => {
})
it('should allow a user to be created', async () => {
const response = await fetch(`${apiUrl}/${slug}`, {
const response = await restClient.POST(`/${slug}`, {
body: JSON.stringify({
email: 'name@test.com',
password,
@@ -279,9 +256,7 @@ describe('Auth', () => {
}),
headers: {
Authorization: `JWT ${token}`,
'Content-Type': 'application/json',
},
method: 'post',
})
const data = await response.json()
@@ -299,7 +274,7 @@ describe('Auth', () => {
it('should allow verification of a user', async () => {
const emailToVerify = 'verify@me.com'
const response = await fetch(`${apiUrl}/public-users`, {
const response = await restClient.POST(`/public-users`, {
body: JSON.stringify({
email: emailToVerify,
password,
@@ -307,9 +282,7 @@ describe('Auth', () => {
}),
headers: {
Authorization: `JWT ${token}`,
'Content-Type': 'application/json',
},
method: 'post',
})
expect(response.status).toBe(201)
@@ -330,14 +303,8 @@ describe('Auth', () => {
expect(_verified).toBe(false)
expect(_verificationToken).toBeDefined()
const verificationResponse = await fetch(
`${apiUrl}/public-users/verify/${_verificationToken}`,
{
headers: {
'Content-Type': 'application/json',
},
method: 'post',
},
const verificationResponse = await restClient.POST(
`/public-users/verify/${_verificationToken}`,
)
expect(verificationResponse.status).toBe(200)
@@ -365,15 +332,13 @@ describe('Auth', () => {
let data
beforeAll(async () => {
const response = await fetch(`${apiUrl}/payload-preferences/${key}`, {
const response = await restClient.POST(`/${slug}/payload-preferences/${key}`, {
body: JSON.stringify({
value: { property },
}),
headers: {
Authorization: `JWT ${token}`,
'Content-Type': 'application/json',
},
method: 'post',
})
data = await response.json()
})
@@ -384,12 +349,10 @@ describe('Auth', () => {
})
it('should read', async () => {
const response = await fetch(`${apiUrl}/payload-preferences/${key}`, {
const response = await restClient.GET(`/${slug}/payload-preferences/${key}`, {
headers: {
Authorization: `JWT ${token}`,
'Content-Type': 'application/json',
},
method: 'get',
})
data = await response.json()
expect(data.key).toStrictEqual(key)
@@ -397,15 +360,13 @@ describe('Auth', () => {
})
it('should update', async () => {
const response = await fetch(`${apiUrl}/payload-preferences/${key}`, {
const response = await restClient.POST(`/${slug}/payload-preferences/${key}`, {
body: JSON.stringify({
value: { property: 'updated', property2: 'test' },
}),
headers: {
Authorization: `JWT ${token}`,
'Content-Type': 'application/json',
},
method: 'post',
})
data = await response.json()
@@ -426,14 +387,11 @@ describe('Auth', () => {
})
it('should delete', async () => {
const response = await fetch(`${apiUrl}/payload-preferences/${key}`, {
const response = await restClient.DELETE(`/${slug}/payload-preferences/${key}`, {
headers: {
Authorization: `JWT ${token}`,
'Content-Type': 'application/json',
},
method: 'delete',
})
data = await response.json()
const result = await payload.find({
@@ -452,43 +410,34 @@ describe('Auth', () => {
const userEmail = 'lock@me.com'
const tryLogin = async () => {
await fetch(`${apiUrl}/${slug}/login`, {
await restClient.POST(`/${slug}/login`, {
body: JSON.stringify({
email: userEmail,
password: 'bad',
}),
headers: {
'Content-Type': 'application/json',
},
method: 'post',
})
// expect(loginRes.status).toEqual(401);
}
beforeAll(async () => {
const response = await fetch(`${apiUrl}/${slug}/login`, {
const response = await restClient.POST(`/${slug}/login`, {
body: JSON.stringify({
email,
password,
}),
headers,
method: 'post',
})
const data = await response.json()
token = data.token
// New user to lock
await fetch(`${apiUrl}/${slug}`, {
await restClient.POST(`/${slug}`, {
body: JSON.stringify({
email: userEmail,
password,
}),
headers: {
Authorization: `JWT ${token}`,
'Content-Type': 'application/json',
},
method: 'post',
})
})
@@ -531,16 +480,14 @@ describe('Auth', () => {
})
// login
await fetch(`${apiUrl}/${slug}/login`, {
await restClient.POST(`/${slug}/login`, {
body: JSON.stringify({
email: userEmail,
password,
}),
headers: {
Authorization: `JWT ${token}`,
'Content-Type': 'application/json',
},
method: 'post',
})
const userResult = await payload.find({
@@ -564,16 +511,11 @@ describe('Auth', () => {
it('should allow forgot-password by email', async () => {
// TODO: Spy on payload sendEmail function
const response = await fetch(`${apiUrl}/${slug}/forgot-password`, {
const response = await restClient.POST(`/${slug}/forgot-password`, {
body: JSON.stringify({
email,
}),
headers: {
'Content-Type': 'application/json',
},
method: 'post',
})
// expect(mailSpy).toHaveBeenCalled();
expect(response.status).toBe(200)
@@ -613,21 +555,22 @@ describe('Auth', () => {
},
})
const response = await fetch(`${apiUrl}/${slug}/login`, {
const response = await restClient.POST(`/${slug}/login`, {
body: JSON.stringify({
email: 'insecure@me.com',
password: 'test',
}),
headers,
method: 'post',
})
const data = await response.json()
const adminMe = await fetch(`${apiUrl}/${slug}/me`, {
headers: {
Authorization: `JWT ${data.token}`,
},
}).then((res) => res.json())
const adminMe = await restClient
.GET(`/${slug}/me`, {
headers: {
Authorization: `JWT ${data.token}`,
},
})
.then((res) => res.json())
expect(adminMe.user.adminOnlyField).toEqual('admin secret')
await payload.update({
@@ -638,21 +581,21 @@ describe('Auth', () => {
},
})
const editorMe = await fetch(`${apiUrl}/${slug}/me`, {
headers: {
Authorization: `JWT ${adminMe?.token}`,
},
}).then((res) => res.json())
const editorMe = await restClient
.GET(`/${slug}/me`, {
headers: {
Authorization: `JWT ${data.token}`,
},
})
.then((res) => res.json())
expect(editorMe.user.adminOnlyField).toBeUndefined()
})
it('should not allow refreshing an invalid token', async () => {
const response = await fetch(`${apiUrl}/${slug}/refresh-token`, {
const response = await restClient.POST(`/${slug}/refresh-token`, {
body: JSON.stringify({
token: 'INVALID',
}),
headers,
method: 'post',
})
const data = await response.json()
@@ -678,19 +621,19 @@ describe('Auth', () => {
const [user1, user2] = usersQuery.docs
const success = await fetch(`${apiUrl}/api-keys/${user2.id}`, {
headers: {
Authorization: `api-keys API-Key ${user2.apiKey}`,
'Content-Type': 'application/json',
},
}).then((res) => res.json())
const success = await restClient
.GET(`/api-keys/${user2.id}`, {
headers: {
Authorization: `api-keys API-Key ${user2.apiKey}`,
},
})
.then((res) => res.json())
expect(success.apiKey).toStrictEqual(user2.apiKey)
const fail = await fetch(`${apiUrl}/api-keys/${user1.id}`, {
const fail = await restClient.GET(`/api-keys/${user1.id}`, {
headers: {
Authorization: `api-keys API-Key ${user2.apiKey}`,
'Content-Type': 'application/json',
},
})

View File

@@ -0,0 +1,94 @@
import type { SanitizedConfig } from '../../packages/payload/types'
import { GRAPHQL_POST as createGraphqlPOST } from '../../packages/next/src/routes/graphql'
import {
DELETE as createDELETE,
GET as createGET,
PATCH as createPATCH,
POST as createPOST,
} from '../../packages/next/src/routes/rest'
type ValidPath = `/${string}`
export class NextRESTClient {
private _DELETE: (request: Request, args: { params: { slug: string[] } }) => Promise<Response>
private _GET: (request: Request, args: { params: { slug: string[] } }) => Promise<Response>
private _GRAPHQL_POST: (request: Request) => Promise<Response>
private _PATCH: (request: Request, args: { params: { slug: string[] } }) => Promise<Response>
private _POST: (request: Request, args: { params: { slug: string[] } }) => Promise<Response>
private readonly config: SanitizedConfig
serverURL: string = 'http://localhost:3000'
constructor(config: SanitizedConfig) {
this.config = config
if (config?.serverURL) this.serverURL = config.serverURL
this._GET = createGET(config)
this._POST = createPOST(config)
this._DELETE = createDELETE(config)
this._PATCH = createPATCH(config)
this._GRAPHQL_POST = createGraphqlPOST(config)
}
private generateRequestParts(path: string): {
slug: string[]
url: string
} {
const safePath = path.slice(1)
const slug = safePath.split('/')
const url = `${this.serverURL}${this.config.routes.api}/${safePath}`
return {
url,
slug,
}
}
async DELETE(path: ValidPath, options: RequestInit): Promise<Response> {
const { url, slug } = this.generateRequestParts(path)
const request = new Request(url, { ...options, method: 'DELETE' })
return this._DELETE(request, { params: { slug } })
}
async GET(path: ValidPath, options?: Omit<RequestInit, 'body'>): Promise<Response> {
const { url, slug } = this.generateRequestParts(path)
const request = new Request(url, { ...options, method: 'GET' })
return this._GET(request, { params: { slug } })
}
async GRAPHQL_POST(options: RequestInit): Promise<Response> {
const request = new Request(`${this.serverURL}${this.config.routes.graphQL}`, {
...options,
method: 'POST',
headers: new Headers({
'Content-Type': 'application/json',
...(options?.headers || {}),
}),
})
return this._GRAPHQL_POST(request)
}
async PATCH(path: ValidPath, options: RequestInit): Promise<Response> {
const { url, slug } = this.generateRequestParts(path)
const request = new Request(url, { ...options, method: 'PATCH' })
return this._PATCH(request, { params: { slug } })
}
async POST(path: ValidPath, options?: RequestInit): Promise<Response> {
const { url, slug } = this.generateRequestParts(path)
const request = new Request(url, {
...options,
method: 'POST',
headers: new Headers({
'Content-Type': 'application/json',
...(options?.headers || {}),
}),
})
return this._POST(request, { params: { slug } })
}
}