Skip to content

Commit

Permalink
convert
Browse files Browse the repository at this point in the history
  • Loading branch information
HTSagara committed Aug 9, 2024
1 parent a7f9bb2 commit b759ff5
Show file tree
Hide file tree
Showing 2 changed files with 82 additions and 37 deletions.
76 changes: 63 additions & 13 deletions src/model/fragment.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ const { randomUUID } = require('crypto');
// Use https://www.npmjs.com/package/content-type to create/parse Content-Type headers
const contentType = require('content-type');

const markdown = require('markdown-it')();
const { Buffer } = require('buffer');

// Functions for working with fragment metadata/data using our DB
const {
readFragment,
Expand Down Expand Up @@ -160,19 +163,66 @@ class Fragment {
].includes(type);
}

// /**
// * Convert fragment data to a specified format
// * @param {string} format the format to convert to (e.g., 'html')
// * @returns {Buffer}
// */
// async convertTo(format) {
// const data = await this.getData();
// if (this.type === 'text/markdown' && format === 'html') {
// const html = md.render(data.toString());
// return Buffer.from(html);
// }
// throw new Error(`Unsupported conversion: ${this.type} to ${format}`);
// }
/**
* Convert fragment data to a specified format
* @param {string} format the format to convert to (e.g., 'html')
* @returns {Promise<Buffer>}
*/
async convertFragment(fragment, ext) {
const data = await fragment.getData();

switch (fragment.mimeType) {
case 'text/plain':
if (ext === 'txt') {
return { data, mimeType: 'text/plain' };
}
break;
case 'text/markdown':
if (ext === 'html') {
return { data: Buffer.from(markdown.render(data.toString())), mimeType: 'text/html' };
} else if (ext === 'txt') {
return { data, mimeType: 'text/plain' };
}
break;
case 'text/html':
if (ext === 'txt') {
return { data: Buffer.from(data.toString()), mimeType: 'text/plain' };
} else if (ext === 'html') {
return { data, mimeType: 'text/html' };
}
break;
// Add more cases for other fragment types and their conversions
// Handle images
case 'image/png':
case 'image/jpeg':
case 'image/webp':
case 'image/gif':
case 'image/avif':
if (['png', 'jpg', 'webp', 'gif', 'avif'].includes(ext)) {
return { data, mimeType: `image/${ext}` };
}
break;
// Handle JSON and YAML
case 'application/json':
if (ext === 'json') {
return { data, mimeType: 'application/json' };
} else if (ext === 'txt') {
return { data: Buffer.from(data.toString()), mimeType: 'text/plain' };
}
break;
case 'application/yaml':
if (ext === 'yaml') {
return { data, mimeType: 'application/yaml' };
} else if (ext === 'txt') {
return { data: Buffer.from(data.toString()), mimeType: 'text/plain' };
}
break;
default:
return null;
}

return null;
}
}

module.exports.Fragment = Fragment;
43 changes: 19 additions & 24 deletions src/routes/api/getById.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,42 +4,37 @@ const { createErrorResponse } = require('../../response');
const { Fragment } = require('../../model/fragment');
const logger = require('../../logger');
const path = require('path');
// const md = require('markdown-it')();

module.exports = async (req, res) => {
// separating the ID and extension from the URL
const pathURL = path.parse(req.params.id);

const ext = pathURL.ext.slice(1) || '';
const id = pathURL.name;
// Extract the ID and extension from the URL
const { ext, name: id } = path.parse(req.params.id);
const ownerId = req.user;
logger.info({ ext, id }, 'Extension and ID passed in the URL');
try {
// Looking for the user id in the current fragment data
const frags = await Fragment.byId(ownerId, id);
let data = await frags.getData();

// returns an existing fragment's data converted to a supported type.
// Initially, you only need to support Markdown fragments (.md) converted to HTML (.html) using markdown-it
logger.info({ ext, id }, 'Received request to get fragment with ID and extension');

try {
// Retrieve the fragment by ID and ownerId
const fragment = await Fragment.byId(ownerId, id);
let data = await fragment.getData();

// Check if it has a .md extension
// If an extension is provided, attempt to convert the fragment
if (ext) {
if (ext === 'md') {
// Changes the content type to html
res.set('Content-Type', 'text/html');
res.status(200).send(data);
// Attempt to convert the fragment based on its type and the extension
const convertedData = await Fragment.convertFragment(fragment, ext);
if (convertedData) {
res.set('Content-Type', convertedData.mimeType);
res.status(200).send(convertedData.data);
} else {
// If the extension used represents an unknown or unsupported type,
// or if the fragment cannot be converted to this type, an HTTP 415 error is returned
res.status(415).json(createErrorResponse(415, 'Unknown or unsupported type'));
// Unsupported conversion
res.status(415).json(createErrorResponse(415, 'Unsupported conversion type'));
}
} else {
res.set('Content-Type', frags.type);
// No conversion needed, return the original data
res.set('Content-Type', fragment.type);
res.status(200).send(data);
return;
}
} catch (error) {
logger.warn({ errorMessage: error.message }, 'request to non-existent fragment was made');
logger.warn({ errorMessage: error.message }, 'Fragment not found');
res.status(404).json(createErrorResponse(404, 'Fragment not found'));
}
};

0 comments on commit b759ff5

Please sign in to comment.