Created
August 13, 2019 06:56
-
-
Save epalaz/0439319f8a16238316892892680999cd to your computer and use it in GitHub Desktop.
Server File for GraphQL Server with File Upload
This file contains hidden or 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
const { ApolloServer, gql } = require('apollo-server'); | |
const AWS = require('aws-sdk') | |
const fs = require('fs') | |
AWS.config.loadFromPath('./credentials.json'); | |
const s3 = new AWS.S3({apiVersion: '2006-03-01'}); | |
const typeDefs = gql` | |
type File { | |
filename: String! | |
mimetype: String! | |
encoding: String! | |
} | |
type Query { | |
_ : Boolean | |
} | |
type Mutation { | |
singleUpload(file: Upload!): File!, | |
singleUploadStream(file: Upload!): File! | |
} | |
`; | |
const resolvers = { | |
Mutation: { | |
singleUpload: (parent, args) => { | |
return args.file.then(file => { | |
const {createReadStream, filename, mimetype} = file | |
const fileStream = createReadStream() | |
fileStream.pipe(fs.createWriteStream(`./uploadedFiles/${filename}`)) | |
return file; | |
}); | |
}, | |
singleUploadStream: async (parent, args) => { | |
const file = await args.file | |
const {createReadStream, filename, mimetype} = file | |
const fileStream = createReadStream() | |
const uploadParams = {Bucket: 'apollo-file-upload-test', Key: filename, Body: fileStream}; | |
const result = await s3.upload(uploadParams).promise() | |
console.log(result) | |
return file; | |
} | |
}, | |
}; | |
const server = new ApolloServer({ typeDefs, resolvers }); | |
server.listen().then(({ url }) => { | |
console.log(`\`🚀 Server ready at ${url}`); | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment