hribb / graphql-server-express-upload Goto Github PK
View Code? Open in Web Editor NEWGraphql Server Express file upload middleware
License: MIT License
Graphql Server Express file upload middleware
License: MIT License
We should probably support FileLists nested in variables. It's common to pass an input type rather than scalars for mutation and query params. It seems like a simple bit of recursion could make this work.
Hi @HriBB ,
I'm not sure about the following. Any suggestion?
The Apollo Server Express setup suggests to use bodyParser.json()
:
app.use('/graphql', bodyParser.json(), graphqlExpress({ schema: myGraphQLSchema }));
Your suggested setup makes no note of bodyParser.json()
:
app.use('/graphql',
upload.array('files'),
// after multer and before graphqlExpress
graphqlExpressUpload({ endpointURL: '/graphql' }),
graphqlExpress((req) => {
return {
schema,
context: {}
}
})
)
As you suggest that order is important: where should I put bodyParser.json()
?
hi, I'm try to use this package to upload a file following instruction, but I got a blob url instead file. Here is my code:
in server.js
:
{...}
import graphqlExpressUpload from 'graphql-server-express-upload'
import multer from "multer";
//used your interface package when create apollo server
import { createApolloServer } from 'meteor/apollo';
const WS_PORT = 8083;
const schema = makeExecutableSchema({
typeDefs:Schema,
resolvers:resolveFunctions,
});
createApolloServer({
schema,
},{ graphiql:true});
const httpServer = createServer((request, response) => {
response.writeHead(404);
response.end();
});
httpServer.listen(WS_PORT);
const server = new SubscriptionServer({ subscriptionManager }, httpServer);
const app = express();
const storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, 'uploads');
},
filename: function (req, file, callback) {
console.log(file);
var filename = file.originalname;
var fileExtension = filename.split(".")[1];
callback(null, Date.now() + "." + fileExtension);
}
});
const upload = multer({
storage: storage
});
app.use('/graphql',
upload.array('files'),
bodyParser.json(),
graphqlExpressUpload({ endpointURL: '/graphql' }), // after multer and before graphqlExpress
graphqlExpress((req) => {
console.log('req', req);
return {
schema,
context: {}
}
})
);
app.use('/graphiql', graphiqlExpress({
endpointURL: '/graphql',
}));
in resolver.js
async uploadProfilePicture(root, { id, files }, context) {
//the result of files was like [ { preview: 'blob:http://localhost:3000/8d38f565-7846' } ] }
console.log('uploadProfilePicture', { id, files })
return uploadProfilePicture(id, files);
},
in the result I got a blob url like { preview: 'blob:http://localhost:3000/8d38f565-7846' }
Please help.
Hi @HriBB,
In the readme.md
file the function parseJSONLiteral(ast)
references Kind.STRING
, Kind.BOOLEAN
, Kind.INT
, Kind.FLOAT
, Kind.OBJECT
.
Where are these coming from? / How should I define them?
From the readme.md
:
function parseJSONLiteral(ast) {
switch (ast.kind) {
case Kind.STRING:
case Kind.BOOLEAN:
return ast.value;
case Kind.INT:
case Kind.FLOAT:
return parseFloat(ast.value);
case Kind.OBJECT: {
const value = Object.create(null);
ast.fields.forEach(field => {
value[field.name.value] = parseJSONLiteral(field.value);
});
return value;
}
case Kind.LIST:
return ast.values.map(parseJSONLiteral);
default:
return null;
}
}
@HriBB After reading the docs and checking package.json
, I'd suggest to add multer
to the peer dependencies.
@HriBB Do you perhaps have an example how to handle the file on the graphql server?
If I forward it to my REST endpoint, it doesn't seem to be recognised as a file.
My resolver:
...
uploadUserAvatar(root: Function, args: Object) {
console.log(args.files) // see output below
Viewer.uploadAvatar(args.token, args.files[0])
return Viewer.fromToken(args.token)
}
...
Viewer connection:
uploadAvatar(token: string, avatar: Object){
const options = {
method: 'POST',
uri: this.buildRestURL('settings/profile/uploadavatar'),
headers: {
'Authorization': `Bearer ${token}`,
},
body: {
avatar,
},
json: true,
}
return rp(options)
.then((res) => {
console.log("\nuploadAvatar SUCCESS:", res)
return {
...res.data,
token
}
})
.catch((err) => console.log("\nuploadAvatar ERROR:", err))
Console.log(args.files) from resolver:
[ { fieldname: 'files',
originalname: 'elephant.jpeg',
encoding: '7bit',
mimetype: 'image/jpeg',
destination: '../tmp/',
filename: '5b4af2fa02e1cfde3995873a2d7ea959',
path: '../tmp/5b4af2fa02e1cfde3995873a2d7ea959',
size: 3536 } ] }
Step 3 in the instructions, "Add UploadedFile resolver" is too hard to follow.
Pasting the example code into a typical Apollo resolvers.js file wont work because Kind
is undefined. Where does that come from, how do you import it? And what is this ast
parameter?
This looks pretty boilerplate, why not export the scalar resolver for easy setup?
Something like:
import {UploadedFileResolver} from 'graphql-server-express-upload'
export default {
UploadedFile: UploadedFileResolver,
Query: { ... },
Mutation: { ... }
}
In the meantime, I can't work out how to get the resolver to work so any clarification would be super helpful.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.