|
| 1 | +import { FastifyInstance } from 'fastify' |
| 2 | +import { FromSchema } from 'json-schema-to-ts' |
| 3 | +import { AuthenticatedRequest, Bucket } from '../../types/types' |
| 4 | +import { getPostgrestClient, transformPostgrestError } from '../../utils' |
| 5 | +import { createDefaultSchema, createResponse } from '../../utils/generic-routes' |
| 6 | + |
| 7 | +const updateBucketBodySchema = { |
| 8 | + type: 'object', |
| 9 | + properties: { |
| 10 | + public: { type: 'boolean', example: false }, |
| 11 | + }, |
| 12 | +} as const |
| 13 | +const updateBucketParamsSchema = { |
| 14 | + type: 'object', |
| 15 | + properties: { |
| 16 | + bucketId: { type: 'string', example: 'avatars' }, |
| 17 | + }, |
| 18 | + required: ['bucketId'], |
| 19 | +} as const |
| 20 | + |
| 21 | +const successResponseSchema = { |
| 22 | + type: 'object', |
| 23 | + properties: { |
| 24 | + message: { type: 'string', example: 'Successfully updated' }, |
| 25 | + }, |
| 26 | + required: ['message'], |
| 27 | +} |
| 28 | +interface updateBucketRequestInterface extends AuthenticatedRequest { |
| 29 | + Body: FromSchema<typeof updateBucketBodySchema> |
| 30 | + Params: FromSchema<typeof updateBucketParamsSchema> |
| 31 | +} |
| 32 | + |
| 33 | +// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types |
| 34 | +export default async function routes(fastify: FastifyInstance) { |
| 35 | + const summary = 'Update properties of a bucket' |
| 36 | + const schema = createDefaultSchema(successResponseSchema, { |
| 37 | + body: updateBucketBodySchema, |
| 38 | + summary, |
| 39 | + tags: ['bucket'], |
| 40 | + }) |
| 41 | + fastify.put<updateBucketRequestInterface>( |
| 42 | + '/:bucketId', |
| 43 | + { |
| 44 | + schema, |
| 45 | + }, |
| 46 | + async (request, response) => { |
| 47 | + const authHeader = request.headers.authorization |
| 48 | + const jwt = authHeader.substring('Bearer '.length) |
| 49 | + const postgrest = getPostgrestClient(jwt) |
| 50 | + const { bucketId } = request.params |
| 51 | + |
| 52 | + const { public: isPublic } = request.body |
| 53 | + |
| 54 | + const { error, status } = await postgrest |
| 55 | + .from<Bucket>('buckets') |
| 56 | + .update({ |
| 57 | + public: isPublic, |
| 58 | + }) |
| 59 | + .match({ id: bucketId }) |
| 60 | + .single() |
| 61 | + |
| 62 | + if (error) { |
| 63 | + request.log.error({ error }, 'error updating bucket') |
| 64 | + return response.status(400).send(transformPostgrestError(error, status)) |
| 65 | + } |
| 66 | + return response.status(200).send(createResponse('Successfully updated')) |
| 67 | + } |
| 68 | + ) |
| 69 | +} |
0 commit comments