// resolvers.js
const { createReadStream } = require('fs');
const { Readable } = require('stream');
const { parse } = require('csv-parse/sync');
// Define resolvers for GraphQL schema
const resolvers = {
Mutation: {
// Resolver for reading uploaded CSV file
readUploadedCsv: async (parent, { file }) => {
try {
// Retrieve the file stream from the Upload scalar
const fileStream = await file;
// Validate file type and size
if (!fileStream || fileStream.mimetype !== 'text/csv') {
throw new Error('Only CSV files are supported');
}
if (fileStream.size > 10000000) {
throw new Error('File size exceeds the 10MB limit');
}
// Convert file stream to a readable buffer
const readableStream = new Readable({
read() {}, // Required for Readable implementation
});
// Pipe the file stream into the readable stream
fileStream.stream().pipe(readableStream);
// Convert stream to buffer
const fileBuffer = await streamToBuffer(readableStream);
// Parse CSV data from the buffer
const csvData = parse(fileBuffer, {
from_line: 1, // Optional: Skip header row
});
// Format and return parsed CSV rows
return csvData.map((row) => row.join(','));
} catch (error) {
// Log and rethrow error for better debugging
console.error('Error reading CSV file:', error);
throw error;
}
},
},
};
// Helper function to convert stream to buffer
function streamToBuffer(stream) {
return new Promise((resolve, reject) => {
const chunks = [];
stream.on('data', (chunk) => chunks.push(chunk));
stream.on('error', (err) => reject(err));
stream.on('end', () => resolve(Buffer.concat(chunks)));
});
}
module.exports = { resolvers };
javascript
// server.js
const fastify = require('fastify')();
const { graphqlPlugin } = require('@pothos/plugin-fastify');
const { graphqlSchemaPlugin } = require('@pothos/core');
const { UploadGraphQLPlugin } = require('@pothos/plugin-upload');
const { resolvers } = require('./resolvers');
const { typeDefs } = require('./schema');
// Register Fastify GraphQL plugin with schema and upload support
fastify.register(graphqlPlugin, {
// Define GraphQL schema with resolvers
graphqlSchema: new graphqlSchemaPlugin({
typeDefs,
resolvers,
}),
// Configure upload settings
upload: {
maxFileSize: 10 * 1024 * 1024, // 10MB file size limit
},
});
// Register Upload GraphQL plugin for file handling
fastify.register(UploadGraphQLPlugin);
// Start the server and listen on port 3000
fastify.listen(3000, (err) => {
if (err) throw err;
console.log(`Server listening on http://localhost:3000/graphql`);
});
Note: Ensure to install the required packages by running npm install pothos-graphql fastify @pothos/plugin-fastify @pothos/core @pothos/plugin-upload csv-parse or the equivalent yarn commands.
This setup assumes a basic understanding of the involved technologies. Adjust file paths and configurations according to your project structure.
Testing the Mutation:
To test the readUploadedCsv mutation, use a GraphQL client like GraphQL Playground or a tool like curl with a valid CSV file. Here’s an example using curl: