2023-07-23 15:08:43 +00:00
|
|
|
import { GraphQLError } from 'graphql'
|
2024-03-20 00:37:31 +00:00
|
|
|
import { ANON_USER_ID, IMAGE_PIXELS_MAX, UPLOAD_SIZE_MAX, UPLOAD_SIZE_MAX_AVATAR, UPLOAD_TYPES_ALLOW } from '@/lib/constants'
|
|
|
|
import { createPresignedPost } from '@/api/s3'
|
2022-05-12 18:44:21 +00:00
|
|
|
|
|
|
|
export default {
|
|
|
|
Mutation: {
|
2023-11-06 20:53:33 +00:00
|
|
|
getSignedPOST: async (parent, { type, size, width, height, avatar }, { models, me }) => {
|
2022-05-12 18:44:21 +00:00
|
|
|
if (UPLOAD_TYPES_ALLOW.indexOf(type) === -1) {
|
2023-07-23 15:08:43 +00:00
|
|
|
throw new GraphQLError(`image must be ${UPLOAD_TYPES_ALLOW.map(t => t.replace('image/', '')).join(', ')}`, { extensions: { code: 'BAD_INPUT' } })
|
2022-05-12 18:44:21 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if (size > UPLOAD_SIZE_MAX) {
|
2023-11-06 20:53:33 +00:00
|
|
|
throw new GraphQLError(`image must be less than ${UPLOAD_SIZE_MAX / (1024 ** 2)} megabytes`, { extensions: { code: 'BAD_INPUT' } })
|
|
|
|
}
|
|
|
|
|
|
|
|
if (avatar && size > UPLOAD_SIZE_MAX_AVATAR) {
|
|
|
|
throw new GraphQLError(`image must be less than ${UPLOAD_SIZE_MAX_AVATAR / (1024 ** 2)} megabytes`, { extensions: { code: 'BAD_INPUT' } })
|
2022-05-12 18:44:21 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if (width * height > IMAGE_PIXELS_MAX) {
|
2023-07-23 15:08:43 +00:00
|
|
|
throw new GraphQLError(`image must be less than ${IMAGE_PIXELS_MAX} pixels`, { extensions: { code: 'BAD_INPUT' } })
|
2022-05-12 18:44:21 +00:00
|
|
|
}
|
|
|
|
|
2023-11-06 20:53:33 +00:00
|
|
|
const imgParams = {
|
|
|
|
type,
|
|
|
|
size,
|
|
|
|
width,
|
|
|
|
height,
|
|
|
|
userId: me?.id || ANON_USER_ID,
|
|
|
|
paid: false
|
|
|
|
}
|
2022-05-12 18:44:21 +00:00
|
|
|
|
2023-11-06 20:53:33 +00:00
|
|
|
if (avatar) {
|
|
|
|
if (!me) throw new GraphQLError('you must be logged in', { extensions: { code: 'FORBIDDEN' } })
|
|
|
|
imgParams.paid = undefined
|
|
|
|
}
|
2022-05-12 18:44:21 +00:00
|
|
|
|
2023-11-06 20:53:33 +00:00
|
|
|
const upload = await models.upload.create({ data: { ...imgParams } })
|
|
|
|
return createPresignedPost({ key: String(upload.id), type, size })
|
2022-05-12 18:44:21 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|