-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
createGlobalVersion.ts
47 lines (38 loc) · 1.3 KB
/
createGlobalVersion.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import type { TypeWithVersion } from 'payload/database'
import type { PayloadRequest, TypeWithID } from 'payload/types'
import { sql } from 'drizzle-orm'
import { type CreateGlobalVersionArgs } from 'payload/database'
import { buildVersionGlobalFields } from 'payload/versions'
import toSnakeCase from 'to-snake-case'
import type { PostgresAdapter } from './types'
import { upsertRow } from './upsertRow'
export async function createGlobalVersion<T extends TypeWithID>(
this: PostgresAdapter,
{ autosave, globalSlug, req = {} as PayloadRequest, versionData }: CreateGlobalVersionArgs,
) {
const db = this.sessions[req.transactionID]?.db || this.drizzle
const global = this.payload.globals.config.find(({ slug }) => slug === globalSlug)
const tableName = this.tableNameMap.get(`_${toSnakeCase(global.slug)}${this.versionsSuffix}`)
const result = await upsertRow<TypeWithVersion<T>>({
adapter: this,
data: {
autosave,
latest: true,
version: versionData,
},
db,
fields: buildVersionGlobalFields(global),
operation: 'create',
req,
tableName,
})
const table = this.tables[tableName]
if (global.versions.drafts) {
await db.execute(sql`
UPDATE ${table}
SET latest = false
WHERE ${table.id} != ${result.id};
`)
}
return result
}