Skip to content

Commit 791839a

Browse files
committed
ptch: add x-upsert header to upsert duplicate object
1 parent 215b178 commit 791839a

File tree

1 file changed

+40
-14
lines changed

1 file changed

+40
-14
lines changed

src/routes/object/createObject.ts

Lines changed: 40 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { ServiceOutputTypes } from '@aws-sdk/client-s3'
2+
import { PostgrestSingleResponse } from '@supabase/postgrest-js/dist/main/lib/types'
23
import { FastifyInstance, RequestGenericInterface } from 'fastify'
34
import { FromSchema } from 'json-schema-to-ts'
45
import { Obj, ObjectMetadata } from '../../types/types'
@@ -88,21 +89,46 @@ export default async function routes(fastify: FastifyInstance) {
8889
})
8990
}
9091

91-
const { data: results, error, status } = await postgrest
92-
.from<Obj>('objects')
93-
.insert(
94-
[
92+
const isUpsert =
93+
request.headers['x-upsert'] && request.headers['x-upsert'] === 'true' ? true : false
94+
95+
let postgrestResponse: PostgrestSingleResponse<Obj>
96+
97+
if (isUpsert) {
98+
postgrestResponse = await postgrest
99+
.from<Obj>('objects')
100+
.upsert(
101+
[
102+
{
103+
name: objectName,
104+
owner: owner,
105+
bucket_id: bucketName,
106+
},
107+
],
95108
{
96-
name: objectName,
97-
owner: owner,
98-
bucket_id: bucketName,
99-
},
100-
],
101-
{
102-
returning: 'minimal',
103-
}
104-
)
105-
.single()
109+
onConflict: 'name, bucket_id',
110+
}
111+
)
112+
.single()
113+
} else {
114+
postgrestResponse = await postgrest
115+
.from<Obj>('objects')
116+
.insert(
117+
[
118+
{
119+
name: objectName,
120+
owner: owner,
121+
bucket_id: bucketName,
122+
},
123+
],
124+
{
125+
returning: 'minimal',
126+
}
127+
)
128+
.single()
129+
}
130+
131+
const { error, status, data: results } = postgrestResponse
106132

107133
if (error) {
108134
request.log.error({ error }, 'error object')

0 commit comments

Comments
 (0)