Last active
May 29, 2020 19:55
-
-
Save squamuglia/aaafb0d3082e517f4253e0dec8e6db88 to your computer and use it in GitHub Desktop.
A fastify app for handling multipart form data
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import fastify,{ FastifyInstance } from "fastify"; | |
import cors from "fastify-cors"; | |
import multipart from "fastify-multipart"; | |
import { FastifyInstance } from "fastify"; | |
import cloudinary from "cloudinary"; | |
import { Server, IncomingMessage, ServerResponse } from "http"; | |
const server: FastifyInstance< | |
Server, | |
IncomingMessage, | |
ServerResponse | |
> = fastify(); | |
server.register(cors); | |
server.register(multipart, { | |
addToBody: true, | |
sharedSchemaId: "MultipartFileType", | |
}); | |
cloudinary.config({ | |
cloud_name: "YOUR_CLOUDNAME", | |
api_key: YOUR_CLOUDINARY_API_KEY, | |
api_secret: YOUR_CLOUDINARY_API_SECRET, | |
}); | |
server.route({ | |
method: "POST", | |
url: "/image", | |
handler: async (request, reply) => { | |
if (!request.isMultipart()) { | |
reply.code(400).send(new Error("Request is not multipart")); | |
return; | |
} | |
try { | |
const image = await new Promise((resolve, reject) => { | |
cloudinary.v2.uploader | |
.upload_stream( | |
{ folder: 'images' }, | |
(error, result) => { | |
if (error) { | |
reject(error); | |
} | |
resolve(result); | |
}, | |
) | |
.end(request.body.file[0].data); | |
}); | |
reply.code(200).send({ image }); | |
} catch (err) { | |
reply.code(500).send(err.message); | |
} | |
}, | |
}); | |
server.setErrorHandler((error, _request, reply) => { | |
console.error(error); | |
reply.code(error.statusCode || 500).send(error); | |
}); | |
server.listen(3000, (err, address) => { | |
if (err) throw err; | |
console.log(`server started on ${address}`); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment