Skip to content

Commit

Permalink
ptch: add x-upsert header to upsert duplicate object
Browse files Browse the repository at this point in the history
  • Loading branch information
ankitjena committed Jun 20, 2021
1 parent 215b178 commit 1d23047
Showing 1 changed file with 41 additions and 14 deletions.
55 changes: 41 additions & 14 deletions src/routes/object/createObject.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { ServiceOutputTypes } from '@aws-sdk/client-s3'
import { PostgrestSingleResponse } from '@supabase/postgrest-js/dist/main/lib/types'
import { FastifyInstance, RequestGenericInterface } from 'fastify'
import { FromSchema } from 'json-schema-to-ts'
import { Obj, ObjectMetadata } from '../../types/types'
Expand Down Expand Up @@ -88,21 +89,47 @@ export default async function routes(fastify: FastifyInstance) {
})
}

const { data: results, error, status } = await postgrest
.from<Obj>('objects')
.insert(
[
const isUpsert =
request.headers['x-upsert'] && request.headers['x-upsert'] === 'true' ? true : false

let postgrestResponse: PostgrestSingleResponse<Obj>

if (isUpsert) {
postgrestResponse = await postgrest
.from<Obj>('objects')
.upsert(
[
{
name: objectName,
owner: owner,
bucket_id: bucketName,
},
],
{
name: objectName,
owner: owner,
bucket_id: bucketName,
},
],
{
returning: 'minimal',
}
)
.single()
onConflict: 'name, bucket_id',
returning: 'minimal',
}
)
.single()
} else {
postgrestResponse = await postgrest
.from<Obj>('objects')
.insert(
[
{
name: objectName,
owner: owner,
bucket_id: bucketName,
},
],
{
returning: 'minimal',
}
)
.single()
}

const { error, status, data: results } = postgrestResponse

if (error) {
request.log.error({ error }, 'error object')
Expand Down

0 comments on commit 1d23047

Please sign in to comment.