I am new to GraphQL an do not fully understand its possibilities. However I need to convert my REST request to GraphQL request and here is my question, how can I implement following code in GraphQL?
router.get('/image/:id', (req, res) => {
const path = 'images/' req.params.id '.jpg';
return res.sendFile(path, { root: 'src/' })
})
For my other requests I am working with mongodb database, and I could convert my REST requests to Graphql request, but for this piece of code, I have no idea how to implement that.
Thank you in advance
CodePudding user response:
This isn't something you can recreate with GraphQL. It's a standard for data querying and retrieval and it expects that the response from the GraphQL endpoint be a valid JSON.
The best thing to do is to keep your existing endpoint and use it for fetching images when necessary.
If you're dead set on returning the data through GraphQL, you can also try base64 encoding it so you can convert the binary data into a string that you can convert back into a Buffer on the client.
The resolver for that would look something like this:
import { promises as fs } from "fs";
const getImage = async (_, { id }) => {
const fileBuffer = await fs.readFile("images/" id ".jpg");
return fileBuffer.toString("base64");
}