Untitled
unknown
javascript
a year ago
2.8 kB
12
Indexable
const { Fragment } = require('../../model/fragment');
const { createErrorResponse, createSuccessResponse } = require('../../response');
module.exports = async (req, res) => {
console.log('Received headers:', req.headers);
console.log('Received content-type:', req.headers['content-type']);
try {
console.log('Authenticated user:', req.user);
const ownerId = req.user;
const contentTypeHeader = req.headers['content-type'];
let data = req.body;
console.log('Request Body:', data);
console.log('Content Type Header:', contentTypeHeader);
// Check if the content type is supported
if (!Fragment.isSupportedType(contentTypeHeader)) {
console.warn('Unsupported content type:', contentTypeHeader);
return res.status(415).json(createErrorResponse(415, 'Unsupported content type'));
}
// Handle the incoming data based on content type
if (contentTypeHeader === 'application/json') {
// If the content type is JSON, it should already be parsed to an object by express.json() middleware
if (typeof data === 'object') {
data = JSON.stringify(data);
} else if (typeof data !== 'string') {
console.warn('Invalid JSON data type:', typeof data);
return res.status(400).json(createErrorResponse(400, 'Invalid JSON data type'));
}
data = Buffer.from(data, 'utf-8'); // Convert JSON string to Buffer
} else if (req.is('image/*')) {
// Handle binary data (images, application data, audio, video)
if (Buffer.isBuffer(data)) {
// Data is already a buffer (as expected for binary uploads)
console.log('Received binary data as Buffer');
} else {
console.warn('Unexpected data type for binary content:', typeof data);
return res.status(400).json(createErrorResponse(400, 'Invalid binary data type. Expected binary data.'));
}
} else {
console.warn('Unsupported content type:', contentTypeHeader);
return res.status(415).json(createErrorResponse(415, 'Unsupported content type'));
}
// Calculate the size of the data
const dataSize = data.length; // Buffer length directly for binary data
// Create the fragment with the calculated size
const fragment = new Fragment({ ownerId, type: contentTypeHeader, size: dataSize });
await fragment.setData(data); // Directly use the Buffer
await fragment.save();
console.debug('Fragment created:', fragment);
// Construct the Location URL for the created fragment
const locationURL = `${req.protocol}://${req.get('host')}/v1/fragments/${fragment.id}`;
res.location(locationURL).status(201).json(createSuccessResponse({ fragment }));
} catch (err) {
console.error('Error creating fragment:', err);
res.status(500).json(createErrorResponse(500, 'Internal Server Error'));
}
};
Editor is loading...
Leave a Comment