// GraphQL Schema
const typeDefs = `
type File {
filename: String!
mimetype: String!
encoding: String!
}
type Query {
uploads: [File]
}
type Mutation {
singleUpload(file: Upload!): File!
}
`;
// Resolvers
const resolvers = {
Query: {
uploads: (parent, args) => {
return db.file.findMany();
},
},
Mutation: {
singleUpload: async (parent, { file }) => {
const { createReadStream, filename, mimetype, encoding } = await file;
const stream = createReadStream();
const path = `images/${filename}`;
// Store the file in the filesystem.
await new Promise((resolve, reject) =>
stream
.on("error", error => {
unlink(path, () => {
reject(error);
});
})
.pipe(createWriteStream(path))
// 1. Create the GraphQL schema for the image upload
const { objectType, stringArg, makeSchema } = require("nexus");
const ImageUpload = objectType({
name: "ImageUpload",
definition(t) {
t.string("url")
}
})
const Mutation = objectType({
name: "Mutation",
definition(t) {
t.field("uploadImage", {
type: "ImageUpload",
args: {
file: stringArg({
nullable: false
})
},
resolve: async (_, { file }, { prisma }) => {
// 2. Create a unique file name
const uniqueFileName = new Date().getTime() + "_" + file.name;
// 3. Create the image directory if it does not exist
const uploadDir = "./uploads";
if (!fs.existsSync(uploadDir)) {
fs.mkdirSync(uploadDir);
}
// 4. Save the file to the uploads directory
await fs.writeFileSync(
path.join(__dirname, 'uploads', image.filename),
image.createReadStream(),
);
// 5. Create the GraphQL Mutation
export const Mutation = extendType({
type: 'Mutation',
definition(t) {
t.field('uploadImage', {
type: 'Image',
args: {
file: uploadScalar('file', {
// 6. Pass the max size to the scalar
maxSize: '2mb',
}),
},
resolve: async (parent, { file }, ctx) => {
// 7. Validate the file
if (!file) {
throw new Error('No file provided.');
}
// 8. Create the Image record in the database
const image = await ctx.prisma.createImage({
filename: file.filename,
mimetype: file.mimetype,
encoding: file.encoding,
});
// 9. Return the image
return image;
},
});