Spaces:
Sleeping
Sleeping
File size: 9,087 Bytes
c01955c | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 | import {expressRepre} from "@vashuthegreat/vexpress";
import ApiError from "../utils/ApiError.js";
import asyncHandler from "../utils/asyncHandler.js";
import ApiResponse from "../utils/ApiResponse.js";
import Template from "../models/templates.models.js";
import reder_html from "../helper/ejsEmbeder.helper.js"
import fs from "fs";
import path from "path";
import logger from "../logger/create.logger.js";
export const createTemplate=expressRepre(
{
summary:"upload a template",
FormData:{
temp_data:"json.pdf",
title:"Data Science",
template:"resume.pdf"
},
response:"uploaded template"
},
asyncHandler(
async(req,res)=>{
const {temp_data,title}=req.body
const files = req.files as any;
const templateFile = files?.template?.[0];
const tempDataFile = files?.temp_data?.[0];
if (!templateFile || !title){
throw new ApiError(400,"Invalid template data. Please provide a template file and title.")
}
// Read the uploaded template file content
const templateContent = fs.readFileSync(templateFile.path, "utf-8");
// Handle temp_data (can be file or body string)
let parsedTempData;
if (tempDataFile) {
try {
const tempDataContent = fs.readFileSync(tempDataFile.path, "utf-8");
parsedTempData = JSON.parse(tempDataContent);
} catch (error) {
throw new ApiError(400, "Invalid JSON in temp_data file");
}
} else if (temp_data) {
if (typeof temp_data === "string") {
try {
parsedTempData = JSON.parse(temp_data);
} catch (error) {
throw new ApiError(400, "Invalid JSON in temp_data body");
}
} else {
parsedTempData = temp_data;
}
}
if (!parsedTempData) {
throw new ApiError(400, "Please provide temp_data as a file or in the request body.");
}
const templateData=await Template.create({
template: templateContent,
temp_data: parsedTempData,
title
})
// Clean up the temporary files
if (templateFile && fs.existsSync(templateFile.path)) {
fs.unlinkSync(templateFile.path);
}
if (tempDataFile && fs.existsSync(tempDataFile.path)) {
fs.unlinkSync(tempDataFile.path);
}
if (templateData){
res.status(200).json(new ApiResponse(200,templateData,"Template uploaded successfully"))
}
else{
throw new ApiError(400,"Failed to upload template")
}
}
)
)
export const getTemplates=expressRepre(
{
summary: "get templates",
params:{id:'696c7ba53a981f5c038d009b'},
response: "templates"
},
asyncHandler(
async(req,res)=>{
const { id } = req.params as { id: string };
logger.info(`Fetching template by ID: ${id}`);
if (!id){
throw new ApiError(400,"Invalid template id")
}
// Try to find in database
const templateData = await Template.findById(id).catch(() => null);
if (templateData){
res.status(200).json(new ApiResponse(200,templateData,"Template fetched successfully"))
} else {
throw new ApiError(404, "Template not found");
}
}
)
)
export const getAllTemplates = expressRepre(
{
summary: "Get all templates",
response: "templates"
},
asyncHandler(async (req, res) => {
try {
console.log("getAllTemplates called");
const templateData = await Template.find().lean();
console.log(`Found ${templateData.length} templates in DB`);
if (!templateData || templateData.length === 0) {
// Return empty array gracefully instead of throwing error
return res
.status(200)
.json(new ApiResponse(200, [], "Templates fetched successfully (empty)"));
}
const final_response: any[] = []
templateData.forEach((template: any) => {
try {
const rendered = reder_html(template.template, template.temp_data);
final_response.push({ ...template, to_render: rendered });
} catch (renderErr) {
logger.error(`Error rendering template ${template.title}:`, renderErr);
// Skip this template if it fails to render
}
});
// console.log(final_response)
// agar templates mil gaye
return res
.status(200)
.json(new ApiResponse(200, final_response, "Templates fetched successfully"));
} catch (err) {
logger.error("Error fetching templates:", err);
// database ya server error
throw new ApiError(500, "Internal Server Error");
}
})
);
export const getTemplate_by_data=expressRepre(
{
summary: "get filled template with data",
body:{template_id:'696c7ba53a981f5c038d009b',temp_data:`{
"personal": {
"name": "John Doe",
"title": "Software Engineer",
"phone": "+1 234 567 890",
"email": "john.doe@example.com",
"location": "San Francisco, CA",
"image": {
"enabled": true,
"url": ""
}
},
"summary": "Experienced software engineer with a strong background in full-stack development and a passion for building scalable applications.",
"education": [
{
"year": "2016 - 2020",
"institute": "University of California, Berkeley",
"degree": "Bachelor of Science in Computer Science"
}
],
"skills": [
"JavaScript",
"Node.js",
"React",
"MongoDB",
"Docker",
"Leadership",
"Communication",
"Problem Solving"
],
"soft_skills": [
"Leadership",
"Communication",
"Problem Solving"
],
"languages": [
"English",
"Spanish"
],
"experience": [
{
"role": "Senior Developer",
"duration": "2021 - Present",
"company": "Tech Solutions Inc.",
"description": "Lead a team of 5 developers in building a high-traffic e-commerce platform. Implemented microservices architecture using Node.js and AWS. Optimized database queries, reducing response time by 30%."
},
{
"role": "Junior Developer",
"duration": "2020 - 2021",
"company": "Startup Hub",
"description": "Developed and maintained RESTful APIs for a mobile application. Collaborated with UI/UX designers to implement responsive web interfaces. Participated in code reviews and unit testing."
}
],
"projects": [
{
"title": "AI Resume Builder",
"description": "A web application that generates multiple resume templates dynamically using AI and user data.",
"tech_stack": ["React", "Node.js", "EJS"]
}
],
"certifications": [
"AWS Certified Developer",
"Full Stack Web Development"
],
"achievements": [
"Employee of the Month",
"Winner of Hackathon 2023"
],
"references": [
{
"name": "Jane Smith",
"company": "Tech Solutions Inc.",
"position": "CTO",
"phone": "+1 987 654 321",
"email": "jane.smith@techsolutions.com"
}
],
"someImportantUrls": {
"GitHub": "https://github.com/johndoe",
"LinkedIn": "https://linkedin.com/in/johndoe",
"Portfolio": "https://johndoe.com"
}
}`},
response: "template with filled data"
},
asyncHandler(
async(req,res)=>{
const userAvatar = (req.user as any)?.avatar;
const id=req.body.template_id
if (!id){
throw new ApiError(400,"Invalid template id")
}
// Try to find in database
const templateData = await Template.findById(id).catch(() => null);
const {temp_data}=req.body;
if (!temp_data){
throw new ApiError(400, "temp data is undefined")
}
// Parse temp_data if it's a string
let parsedTempData;
if (typeof temp_data === "string") {
try {
parsedTempData = JSON.parse(temp_data);
} catch (error) {
throw new ApiError(400, "Invalid JSON in temp_data body");
}
} else {
parsedTempData = temp_data;
}
if (templateData){
parsedTempData={...parsedTempData,avatar:userAvatar}
res.status(200).json(new ApiResponse(200,{to_render:reder_html(templateData.template,parsedTempData)},"Template fetched successfully"))
} else {
throw new ApiError(404, "Template not found");
}
}
)
) |