UNPKG

zync-nest-library

Version:

NestJS library with database backup and file upload utilities

171 lines (145 loc) 4.46 kB
export * from "./date"; export * from "./object"; export * from "./helper"; import * as fs from "fs"; import * as path from "path"; import { v4 as uuid } from "uuid"; import { Response } from "express"; import * as shortid from "shortid"; import * as slugify from "slugify"; import { Buffer } from "buffer"; export const mkdir = (dir: string) => { if (fs.existsSync(dir)) { return true; } const dirname = path.dirname(dir); mkdir(dirname); fs.mkdirSync(dir); }; export const uuidFilenameTransform = (filename = "") => { const fileExtension = path.extname(filename); return `${uuid()}${fileExtension}`; }; export const bufferFromBase64 = (base64: string) => { return Buffer.from( base64.replace(/^data:image\/\w+;base64,/, ""), "base64" ) as any; }; export const getBase64FileName = (base64: string) => { const type = base64.split(";")[0].split("/")[1]; return `${uuid()}.${type}`; }; export const getBase64Size = (base64: string) => { let padding, inBytes, base64StringLength; if (base64.endsWith("==")) padding = 2; else if (base64.endsWith("=")) padding = 1; else padding = 0; base64StringLength = base64.length; inBytes = (base64StringLength / 4) * 3 - padding; return inBytes / 1000; }; export const imageThumbnail = async ( uri: string, options?: { percentage: number; responseType: string } ) => { // return await thumbnail(uri, { // jpegOptions: { force: true, quality: 90 }, // } as any); return null; }; export const toSlug = (title: string) => { // Convert title to a URL-friendly format const slug = slugify.default(title, { lower: true, // Convert to lowercase remove: /[*+~.()'"!:@]/g, // Remove special characters }); // Combine slug and unique identifier const productSlug = `${slug}-${shortid.generate()}`; return productSlug; }; export const streamToBase64 = async (stream): Promise<string> => { return new Promise((resolve, reject) => { const chunks: Buffer[] = []; stream.on("data", (chunk) => chunks.push(chunk)); stream.on("end", () => { const buffer = Buffer.concat(chunks); const base64String = buffer.toString("base64"); resolve(base64String); }); stream.on("error", (error) => reject(error)); }); }; export const replaceStr = (value: string, ...args: string[]): string => { args.forEach((arg: string, index: number) => { value = value.replace(`[${index}]`, arg); }); return value; }; export const buildNode = (parentId: string, data: any, depth = 0) => { if (depth >= 3) { // Limit depth if needed return null; } const children: any[] = []; data.forEach((item) => { if (item.parentId?.toString() === parentId?.toString()) { const childNode = { ...((item as any)._doc || item), children: [] }; const subtree = buildNode(item._id, data, depth + 1); if (subtree) { childNode.children = subtree; } children.push(childNode); } }); return children.length > 0 ? children : null; }; export const toQueryString = (obj: Object) => { const keyValuePairs = []; for (let key in obj) { if (obj.hasOwnProperty(key)) { const value = obj[key]; // If the value is an array, repeat the key for each element if (Array.isArray(value)) { value.forEach((element) => { keyValuePairs.push( `${encodeURIComponent(key)}=${encodeURIComponent(element)}` ); }); } else { keyValuePairs.push( `${encodeURIComponent(key)}=${encodeURIComponent(value)}` ); } } } return keyValuePairs.join("&"); }; const FILE_TYES = { pdf: { type: "application/pdf", ext: ".pdf" }, xlsx: { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", ext: ".xlsx", }, }; export const fileDownloadReponse = ( res: Response, buffer: Buffer, fileName: string, fileType: string ) => { // Set response headers res.setHeader("Content-Type", FILE_TYES[fileType].type); // Ensure filename is quoted and fallback to 'download' if not provided const safeFileName = fileName ? `${fileName}${FILE_TYES[fileType].ext}` : `download${FILE_TYES[fileType].ext}`; res.setHeader( "Content-Disposition", `attachment; filename="${encodeURIComponent( safeFileName )}"; filename*=UTF-8''${encodeURIComponent(safeFileName)}` ); // Send the buffer as the response res.send(buffer); };