feat: avoid unnecessary config await in getPayloadHMR (#7045)
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
import type { GeneratedTypes, InitOptions, Payload, SanitizedConfig } from 'payload'
|
||||
import type { InitOptions, Payload, SanitizedConfig } from 'payload'
|
||||
|
||||
import { BasePayload } from 'payload'
|
||||
import WebSocket from 'ws'
|
||||
@@ -6,7 +6,7 @@ import WebSocket from 'ws'
|
||||
let cached: {
|
||||
payload: Payload | null
|
||||
promise: Promise<Payload> | null
|
||||
reload: Promise<boolean> | boolean
|
||||
reload: Promise<void> | boolean
|
||||
} = global._payload
|
||||
|
||||
if (!cached) {
|
||||
@@ -53,17 +53,18 @@ export const reload = async (config: SanitizedConfig, payload: Payload): Promise
|
||||
|
||||
export const getPayloadHMR = async (options: InitOptions): Promise<Payload> => {
|
||||
if (!options?.config) {
|
||||
throw new Error('Error: the payload config is required for getPayload to work.')
|
||||
throw new Error('Error: the payload config is required for getPayloadHMR to work.')
|
||||
}
|
||||
|
||||
if (cached.payload) {
|
||||
const config = await options.config // TODO: check if we can move this inside the cached.reload === true condition
|
||||
|
||||
if (cached.reload === true) {
|
||||
let resolve
|
||||
let resolve: () => void
|
||||
|
||||
// getPayloadHMR is called multiple times, in parallel. However, we only want to run `await reload` once. By immediately setting cached.reload to a promise,
|
||||
// we can ensure that all subsequent calls will wait for the first reload to finish. So if we set it here, the 2nd call of getPayloadHMR
|
||||
// will reach `if (cached.reload instanceof Promise) {` which then waits for the first reload to finish.
|
||||
cached.reload = new Promise((res) => (resolve = res))
|
||||
|
||||
const config = await options.config
|
||||
await reload(config, cached.payload)
|
||||
|
||||
resolve()
|
||||
@@ -77,6 +78,7 @@ export const getPayloadHMR = async (options: InitOptions): Promise<Payload> => {
|
||||
}
|
||||
|
||||
if (!cached.promise) {
|
||||
// no need to await options.config here, as it's already awaited in the BasePayload.init
|
||||
cached.promise = new BasePayload().init(options)
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user