Skip to content

Instantly share code, notes, and snippets.

@timReynolds
Created September 14, 2018 16:34
Show Gist options
  • Save timReynolds/e40205d21a0e29ebfb929d186987c295 to your computer and use it in GitHub Desktop.
Save timReynolds/e40205d21a0e29ebfb929d186987c295 to your computer and use it in GitHub Desktop.
File upload
const { ApolloServer, gql } = require("apollo-server");
const ListingImageApi = require("./ListingImageApi");
const typeDefs = gql`
# Comments in GraphQL are defined with the hash (#) symbol.
type File {
filename: String!
mimetype: String!
encoding: String!
}
type Mutation {
uploadFile(file: Upload!): File!
}
`;
const resolvers = {
Mutation: {
async uploadFile(_parent, args, { dataSources }) {
const { stream, filename, mimetype, encoding } = await args.file;
console.log("FILE", stream, filename, encoding);
// 1. Validate file metadata.
await dataSources.listingImages.addListingImage(args);
return { stream, filename, mimetype, encoding };
}
}
};
const server = new ApolloServer({
typeDefs,
resolvers,
formatError: error => {
console.error(error);
return new Error('Internal server error');
},
dataSources: () => {
return {
listingImages: new ListingImageApi()
};
}
});
server.listen().then(({ url }) => {
console.log(`🚀 Server ready at ${url}`);
});
const fetch = require("isomorphic-unfetch");
const FormData = require("form-data");
class ListingAPI {
async addListingImage(args) {
const fileData = "";
const chunk;
const file = await args.file;
file.stream.on("data", function() {
fileData += chunk;
});
file.stream.on("end", async function() {
const formData = new FormData();
formData.append("file", fileData, file.filename);
const response = await fetch(
"http://localhost.charlesproxy.com:5000/api/listing-image",
{
method: "POST",
body: formData
}
);
console.log("response", JSON.stringify(response));
return;
});
}
}
module.exports = ListingAPI;
{
"name": "poc-listing-ui-api",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "node index.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"apollo-datasource-rest": "^0.1.4",
"apollo-server": "^2.0.2",
"core-js": "^2.5.7",
"form-data": "^2.3.2",
"graphql": "^0.13.2",
"isomorphic-unfetch": "^2.1.1",
"uuid": "^3.3.2"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment