Files
payloadcms/test/helpers/configHelpers.ts

97 lines
2.5 KiB
TypeScript

import swcRegister from '@swc/register'
import getPort from 'get-port'
import { createServer } from 'http'
import next from 'next'
import path from 'path'
import shelljs from 'shelljs'
import { parse } from 'url'
import type { Payload } from '../../packages/payload/src'
import type { InitOptions } from '../../packages/payload/src/config/types'
import { getPayload } from '../../packages/payload/src'
type Options = {
__dirname: string
init?: Partial<InitOptions>
}
type InitializedPayload = { payload: Payload; serverURL: string }
export async function initPayloadE2E(__dirname: string): Promise<InitializedPayload> {
const webpackCachePath = path.resolve(__dirname, '../../node_modules/.cache/webpack')
shelljs.rm('-rf', webpackCachePath)
return initPayloadTest({
__dirname,
init: {
local: false,
},
})
}
export async function initPayloadTest(options: Options): Promise<InitializedPayload> {
process.env.PAYLOAD_CONFIG_PATH = path.resolve(options.__dirname, './config.ts')
const config = (await import(process.env.PAYLOAD_CONFIG_PATH)).default
const initOptions: InitOptions = {
local: true,
config,
...(options.init || {}),
}
process.env.PAYLOAD_DROP_DATABASE = 'true'
process.env.NODE_ENV = 'test'
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore - bad @swc/register types
swcRegister({
sourceMaps: 'inline',
jsc: {
parser: {
syntax: 'typescript',
tsx: true,
},
},
module: {
type: 'commonjs',
},
})
const payload = await getPayload(initOptions)
const port = await getPort()
const serverURL = `http://localhost:${port}`
if (!initOptions?.local) {
// when using middleware `hostname` and `port` must be provided below
const app = next({
dev: true,
hostname: 'localhost',
port,
dir: path.resolve(__dirname, '../REST_API'),
})
const handle = app.getRequestHandler()
await app.prepare()
createServer(async (req, res) => {
try {
const parsedUrl = parse(req.url, true)
await handle(req, res, parsedUrl)
} catch (err) {
console.error('Error occurred handling', req.url, err)
res.statusCode = 500
res.end('internal server error')
}
})
.once('error', (err) => {
console.error(err)
process.exit(1)
})
.listen(port, () => {
console.log(`> Ready on ${serverURL}`)
})
}
return { serverURL, payload }
}