Untitled

mail@pastecode.io avatar
unknown
javascript
a month ago
2.0 kB
2
Indexable
Never
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)
      if (Buffer.isBuffer(data)) {
        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'));
Leave a Comment