Skip to content

Commit

Permalink
Update noteModel, package.json, userController, server, folderRoutes,…
Browse files Browse the repository at this point in the history
… and noteController
  • Loading branch information
horlami228 committed Mar 19, 2024
1 parent 72c6689 commit 324af10
Show file tree
Hide file tree
Showing 12 changed files with 198 additions and 30 deletions.
40 changes: 40 additions & 0 deletions backend_veenote/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 5 additions & 2 deletions backend_veenote/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,24 +7,27 @@
"scripts": {
"build": "rimraf dist && npx tsc",
"prestart": "npm run build",
"start": "node dist/server.js",
"start": "node dist/src/server.js",
"predevStart": "npm run build",
"devStart": "concurrently \"npx tsc -w \" \"nodemon --inspect dist/server.js\""
"devStart": "concurrently \"npx tsc -w \" \"nodemon dist/src/server.js\""
},
"author": "",
"license": "ISC",
"dependencies": {
"casual": "^1.6.2",
"concurrently": "^8.2.2",
"ejs": "^3.1.9",
"express": "^4.18.2",
"express-ejs-layouts": "^2.5.1",
"faker": "^6.6.6",
"mongoose": "^8.1.1",
"rimraf": "^5.0.5",
"swagger-jsdoc": "^6.2.8",
"swagger-ui-express": "^5.0.0"
},
"devDependencies": {
"@types/express": "^4.17.21",
"@types/faker": "^6.6.9",
"@types/mongoose": "^5.11.97",
"@types/node": "^20.11.16",
"@types/swagger-jsdoc": "^6.0.4",
Expand Down
70 changes: 67 additions & 3 deletions backend_veenote/src/controller/folderController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,19 @@
import {Request, Response} from 'express';
// Importing the User model from the userModel.js file, which defines the schema for the user documents in the MongoDB database.
import Folder from '../model/folderModel.js';
// Importing the base model from the baseModel.ts file, which defines generic functions
import Note from '../model/noteModel.js';
import mongoose from 'mongoose';
import { getModelBy } from '../utilities/dbFunctions.js';

const objectId = mongoose.Types.ObjectId;

interface filterdNotes {
title: string;
content: string;
fileName: string;
createdAt: string;
updatedAt: string;
}

// Define the 'createUser' controller function as an asynchronous function to handle POST requests for creating a new user.
export const createFolder = async (req: Request, res: Response) => {
Expand All @@ -15,7 +26,7 @@ export const createFolder = async (req: Request, res: Response) => {
return res.status(400).json({"Error": "Not a valid JSON"});
} else if (!("folderName" in req.body)) {
// Responds with a 400 Bad Request error if the 'folderNmae' field is missing in the request body.
return res.status(400).json({"Error": "Missing FolderName"});
return res.status(400).json({"Error": "Missing folder name"});
}
// Extracts the data from the request body.
const folderData = {
Expand Down Expand Up @@ -47,7 +58,7 @@ export const createFolder = async (req: Request, res: Response) => {
};


export const getRootFolder = (req: Request, res: Response) => {
export const getRootFolder = async (req: Request, res: Response) => {
// use the 'find' method on the Folder model to find a root folder by the user_id
// This returns a promise

Expand All @@ -74,3 +85,56 @@ export const getRootFolder = (req: Request, res: Response) => {
});
});
};

export const getNotesForFolder = async (req: Request, res: Response) => {
// Get all Notes for a folder
const folderId = req.params.folderId; // retreive folderId from request
let objFolderId: mongoose.Types.ObjectId;
try {
objFolderId = new objectId(folderId); // convert folderId to objectId
}
catch (error) {
return res.status(400).json({message: "Invalid folderId"});
}

//get all notes to a folder
getModelBy(Note, 'folderId', objFolderId)
.then((notes) => {
if (notes.length === 0) {
return res.status(400).json({message: "Folder is empty"});
}

const filteredNotes: filterdNotes[] = notes.map((note: any) => ({
fileName: note.fileName,
title: note.title,
content: note.content,
createdAt: note.createdAt,
updatedAt: note.updatedAt
}));
(getModelBy(Folder, '_id', objFolderId))
.then((folder: any) => {
if (folder.length === 0) {
return res.status(404).json({message: "Folder not found"});
}

// return all notes in that folder
res.status(200).json({
"folders": [
{
"folderId": folder[0]._id,
"folderName": folder[0].folderName,
"notes": filteredNotes
}
]
});
});
})
.catch(error => {
if (error instanceof Error) {
// error with the query
res.status(500).json({
message: error.message
});
}
});
};
26 changes: 6 additions & 20 deletions backend_veenote/src/controller/noteController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,21 +3,7 @@ import {Request, Response} from 'express';
// Importing the User model from the userModel.js file, which defines the schema for the user documents in the MongoDB database.
import Note from '../model/noteModel.js';
import Folder from '../model/folderModel.js';
// Importing the base model from the baseModel.ts file, which defines generic functions


// Function to generate a formatted date and time string
function getFormattedDateTime() {
const date = new Date();
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0'); // Add leading zero for single-digit months
const day = String(date.getDate()).padStart(2, '0');
const hours = String(date.getHours()).padStart(2, '0');
const minutes = String(date.getMinutes()).padStart(2, '0');
const seconds = String(date.getSeconds()).padStart(2, '0');

return `${year}-${month}-${day}-${hours}-${minutes}-${seconds}`;
}
import getFormattedDateTime from '../utilities/dateTimeGenerator.js';

// Define the 'createUser' controller function as an asynchronous function to handle POST requests for creating a new user.
export const createNote = async (req: Request, res: Response) => {
Expand All @@ -28,23 +14,23 @@ export const createNote = async (req: Request, res: Response) => {
}

// Ensure required fields are present
if (!req.body.id || !req.body.content) {
return res.status(400).json({ message: "ID and content are required fields" });
if (!req.body.content) {
return res.status(400).json({ message: "content is a required field" });
}

// Set default filename if missing
req.body.fileName = req.body.fileName || `default-${getFormattedDateTime()}`;
const fileName = req.body.fileName || `default-${getFormattedDateTime()}`;

// Find the associated folder
const folder = await Folder.findOne({ userId: req.body.id });
const folder = await Folder.findOne({ userId: req.body.userId });

if (!folder) {
return res.status(404).json({ message: "Folder not found" });
}

// Create the note data object
const noteData = {
fileName: req.body.fileName,
fileName: fileName,
content: req.body.content,
userId: req.body.id,
folderId: folder._id
Expand Down
1 change: 0 additions & 1 deletion backend_veenote/src/controller/userController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
import {Request, Response} from 'express';
// Importing the User model from the userModel.js file, which defines the schema for the user documents in the MongoDB database.
import User from '../model/userModel.js';
// Importing the base model from the baseModel.ts file, which defines generic functions
import Folder from '../model/folderModel.js';

// Define the 'createUser' controller function as an asynchronous function to handle POST requests for creating a new user.
Expand Down
1 change: 0 additions & 1 deletion backend_veenote/src/model/noteModel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ interface Vnote extends Document {

const noteSchema: Schema = new Schema<Vnote>({
fileName: {type: String},
title: {type: String, default: "Untitled"},
content: {type: String, required: true},
userId: {type: Schema.Types.ObjectId, ref: "User"},
folderId: {type: Schema.Types.ObjectId, ref: "Folder"},
Expand Down
9 changes: 7 additions & 2 deletions backend_veenote/src/routes/folderRoutes.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Router } from "express";
import { createFolder, getRootFolder } from '../controller/folderController.js';
import { createFolder, getRootFolder, getNotesForFolder } from '../controller/folderController.js';

// Create a new router instance
const router = Router();
Expand All @@ -17,7 +17,12 @@ router.post('/user/create', createFolder);
* GET /folder/getRoot
*/

router.get('/folder/rootfolder', getRootFolder);
router.get('/user/folder/rootfolder', getRootFolder);

/**
* Route for getting notes in a folder
* GET /user/folder/<folderId>/notes
*/
router.get('/user/folder/:folderId/notes', getNotesForFolder);

export default router;
15 changes: 15 additions & 0 deletions backend_veenote/src/routes/noteRoutes.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { Router } from "express";
import { createNote} from '../controller/noteController.js';


// Create a new router instance
const router = Router();

/**
* Route for creating a new note.
* POST /user/create/note/new
* The actual logic for user creation is encapsulated in the createFolder function within the folderController.
*/
router.post('/user/create/note/new', createNote);

export default router;
5 changes: 4 additions & 1 deletion backend_veenote/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import express from 'express';
import userRoutes from "./routes/userRoutes.js";
import folderRoutes from './routes/folderRoutes.js';
import noteRoutes from './routes/noteRoutes.js';
import swaggerSpec from './swaggerConfig.js';
import swaggerUi from 'swagger-ui-express';

Expand All @@ -23,7 +24,9 @@ app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec));
// All API routes are prefixed with '/api/v1'
app.use('/api/v1', userRoutes);

app.use('api/v1', folderRoutes);
app.use('/api/v1', folderRoutes);

app.use('/api/v1', noteRoutes);

// A custom 404 'not found' middleware
app.use((req, res, next) => {
Expand Down
14 changes: 14 additions & 0 deletions backend_veenote/src/utilities/dateTimeGenerator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
// Function to generate a formatted date and time string
function getFormattedDateTime() {
const date = new Date();
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0'); // Add leading zero for single-digit months
const day = String(date.getDate()).padStart(2, '0');
const hours = String(date.getHours()).padStart(2, '0');
const minutes = String(date.getMinutes()).padStart(2, '0');
const seconds = String(date.getSeconds()).padStart(2, '0');

return `${year}-${month}-${day}-${hours}-${minutes}-${seconds}`;
}

export default getFormattedDateTime;
24 changes: 24 additions & 0 deletions backend_veenote/src/utilities/dbFunctions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
// Define a generic type for the model's document type
type TModel<T> = {
find: (conditions: any) => Promise<T[]>; // Adjust return type if needed
};
import mongoose from "mongoose";

export async function getModelBy<T> (
model: TModel<T>,
key: string,
value: mongoose.Types.ObjectId
): Promise<T[]> {
try {
const records = await model.find({ [key]: value });
return records;
} catch (error) {
if (error instanceof Error) {
console.log(error.message);
}
}

// Explicitly return undefined if function reaches here (unexpected)
return [];
}

16 changes: 16 additions & 0 deletions backend_veenote/src/utilities/fakeDataGenerator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import casual from "casual";
import mongoose from "mongoose";
import dateTimeGenerator from "./dateTimeGenerator.js";

const no_name = `default-${dateTimeGenerator()}`;

export function generateNote(folderId: mongoose.Types.ObjectId, userId: mongoose.Types.ObjectId) {
return {
fileName: casual.title, // Use casual.title for filenames
content: casual.sentences(2),
userId: userId,// Generate random content sentences
folderId: folderId,
};
}

// Path: backend_veenote/src/utilities/fakeDataGenerator.ts

0 comments on commit 324af10

Please sign in to comment.