Skip to content

Commit

Permalink
feat(tasks. commit before refactoring): Created functions for editing…
Browse files Browse the repository at this point in the history
… and deleting a task, fixed functional bugs related to the ui
  • Loading branch information
Dedakup committed Nov 25, 2024
1 parent d4a65a1 commit c636835
Show file tree
Hide file tree
Showing 11 changed files with 1,433 additions and 202 deletions.
18 changes: 9 additions & 9 deletions backend/src/handlers/auth/lib.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ const jwksClient = require('jwks-rsa');
const jwt = require('jsonwebtoken');
const util = require('util');

//generating IAM policy
const getPolicyDocument = (effect, resource) => {
const policyDocument = {
Version: '2012-10-17', // default version
Expand Down Expand Up @@ -41,7 +42,6 @@ const jwtOptions = {
};

module.exports.authenticate = (params) => {
console.log(params);
const token = getToken(params);

const decoded = jwt.decode(token, { complete: true });
Expand All @@ -51,20 +51,20 @@ module.exports.authenticate = (params) => {

const getSigningKey = util.promisify(client.getSigningKey);
return getSigningKey(decoded.header.kid)
.then((key) => {
.then((key) => { //veridy token
const signingKey = key.publicKey || key.rsaPublicKey;
return jwt.verify(token, signingKey, jwtOptions);
})
.then((decoded)=> ({
.then((decoded) => ({ //reurn policy document
principalId: decoded.sub,
policyDocument: getPolicyDocument('Allow', params.methodArn),
context: { scope: decoded.scope }
}));
}

const client = jwksClient({
cache: true,
rateLimit: true,
jwksRequestsPerMinute: 10, // Default value
jwksUri: process.env.JWKS_URI
});
const client = jwksClient({
cache: true,
rateLimit: true,
jwksRequestsPerMinute: 10, // Default value
jwksUri: process.env.JWKS_URI
});
11 changes: 7 additions & 4 deletions backend/src/handlers/task/createTask.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
const db = require('../../utils/db');
const { createTaskParams } = require("../../layers/models/taskParams");

module.exports.createTask = async (event) => {
// Log the received body
console.log("Received event body:", event.body);

// parse api request
let taskData;
try {
taskData = JSON.parse(event.body);
Expand All @@ -18,6 +18,7 @@ module.exports.createTask = async (event) => {
};
}

//dave data
const { userId, taskId, title, description, dueDate } = taskData;

// Validate required fields
Expand All @@ -36,6 +37,7 @@ module.exports.createTask = async (event) => {
};
}

//generate model params
const params = {
TableName: process.env.DYNAMODB_TASKS_TABLE,
Item: {
Expand All @@ -49,11 +51,12 @@ module.exports.createTask = async (event) => {
},
};

//add data to the database
try {
const result = await db.put(params);
console.log("DynamoDB PUT Success:", result);
return {
statusCode: 201,
//send cors headers
headers: {
'Access-Control-Allow-Origin': 'http://localhost:5173',
'Access-Control-Allow-Credentials': true,
Expand All @@ -70,5 +73,5 @@ module.exports.createTask = async (event) => {
},
body: JSON.stringify({ error: error.message }),
};
}
}
};
61 changes: 51 additions & 10 deletions backend/src/handlers/task/deleteTask.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,58 @@
const db = require('../../utils/db');
const db = require("../../utils/db");

module.exports.deleteTask = async (event) => {
const { taskId } = event.pathParameters;
//get task id from url
const taskId = event.pathParameters?.taskId;

//validate task id
if (!taskId) {
return {
statusCode: 400,
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Credentials": true,
},
body: JSON.stringify({ error: "Missing path parameter: taskId" }),
};
}

const userId = event.queryStringParameters?.userId;

if (!userId) {
return {
statusCode: 400,
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Credentials": true,
},
body: JSON.stringify({ error: "Missing query parameter: userId" }),
};
}

const params = {
TableName: process.env.DYNAMODB_TASKS_TABLE,
Key: { userId: event.requestContext.authorizer.userId, taskId },
};

await db.delete(params);
Key: { userId, taskId },
}

return {
statusCode: 200,
body: JSON.stringify({ message: 'Task deleted successfully' }),
};
try {
await db.delete(params);
return {
statusCode: 200,
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Credentials": true,
},
body: JSON.stringify({ message: "Task deleted successfully", taskId }),
};
} catch (error) {
console.error("DynamoDB Delete Error:", error);
return {
statusCode: 500,
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Credentials": true,
},
body: JSON.stringify({ error: error.message }),
};
}
};
15 changes: 5 additions & 10 deletions backend/src/handlers/task/getTask.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
const db = require('../../utils/db');

module.exports.getTasks = async (event) => {
console.log("Starting getTasks handler");

// Get userId from query string parameters
const userId = event.queryStringParameters?.userId;
Expand All @@ -19,20 +18,16 @@ module.exports.getTasks = async (event) => {

// DynamoDB query parameters
const params = {
TableName: process.env.DYNAMODB_TASKS_TABLE, // Ensure the environment variable is correct
KeyConditionExpression: 'userId = :userId', // Query based on the partition key
TableName: process.env.DYNAMODB_TASKS_TABLE,
KeyConditionExpression: "userId = :userId",
ExpressionAttributeValues: {
':userId': userId, // Pass the userId to the query
":userId": userId,
},
};

console.log("UserId:", userId);
console.log("DynamoDB params:", params);
}

//query data
try {
console.log("Attempting DynamoDB query...");
const result = await db.query(params);
console.log("Query result:", result);

return {
statusCode: 200,
Expand Down
72 changes: 61 additions & 11 deletions backend/src/handlers/task/updateTask.js
Original file line number Diff line number Diff line change
@@ -1,20 +1,70 @@
const db = require('../../utils/db');

module.exports.updateTask = async (event) => {
const { taskId } = event.pathParameters;
const { title, description, dueDate, status } = JSON.parse(event.body);
const { taskId, userId, ...updatedFields } = JSON.parse(event.body);

if (!taskId || !userId || Object.keys(updatedFields).length === 0) {
return {
statusCode: 400,
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Credentials": true,
},
body: JSON.stringify({
error: "Missing required parameters or body",
}),
};
}

const updateExpressions = [];
const expressionAttributeNames = {};
const expressionAttributeValues = {};

Object.keys(updatedFields).forEach((field, index) => {
const attributeName = `#field${index}`;
const attributeValue = `:value${index}`;

updateExpressions.push(`${attributeName} = ${attributeValue}`);
expressionAttributeNames[attributeName] = field;
expressionAttributeValues[attributeValue] = updatedFields[field];
});

const params = {
TableName: process.env.DYNAMODB_TASKS_TABLE,
Key: { userId: event.requestContext.authorizer.userId, taskId },
UpdateExpression: 'set title = :title, description = :description, dueDate = :dueDate, status = :status',
ExpressionAttributeValues: { ':title': title, ':description': description, ':dueDate': dueDate, ':status': status },
Key: {
userId,
taskId,
},
UpdateExpression: `SET ${updateExpressions.join(', ')}`,
ExpressionAttributeNames: expressionAttributeNames,
ExpressionAttributeValues: expressionAttributeValues,
ReturnValues: "UPDATED_NEW",
};

await db.update(params);

return {
statusCode: 200,
body: JSON.stringify({ message: 'Task updated successfully' }),
};
try {
const result = await db.update(params);
return {
statusCode: 200,
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Credentials": true,
},
body: JSON.stringify({
message: "Task updated successfully",
updatedTask: result.Attributes,
}),
};
} catch (error) {
console.error("Error updating task:", error);
return {
statusCode: 500,
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Credentials": true,
},
body: JSON.stringify({
error: "Failed to update task",
}),
};
}
};
54 changes: 54 additions & 0 deletions backend/src/layers/models/taskParams.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
// src/models/taskParams.js
require('dotenv').config();

const createTaskParams = ({ userId, taskId, title, description, dueDate }) => ({
TableName: process.env.DYNAMODB_TASKS_TABLE,
Item: {
userId,
taskId,
title,
description: description || null,
dueDate: dueDate || null,
status: "pending",
createdAt: new Date().toISOString(),
},
});

const getTasksParams = ({ userId }) => ({
TableName: process.env.DYNAMODB_TASKS_TABLE,
KeyConditionExpression: "userId = :userId",
ExpressionAttributeValues: {
":userId": userId,
},
});

const updateTaskParams = ({ userId, taskId, updates }) => ({
TableName: process.env.DYNAMODB_TASKS_TABLE,
Key: { userId, taskId },
UpdateExpression: "SET #title = :title, #description = :description, #dueDate = :dueDate, #status = :status",
ExpressionAttributeNames: {
"#title": "title",
"#description": "description",
"#dueDate": "dueDate",
"#status": "status",
},
ExpressionAttributeValues: {
":title": updates.title,
":description": updates.description || null,
":dueDate": updates.dueDate || null,
":status": updates.status || "pending",
},
ReturnValues: "UPDATED_NEW",
});

const deleteTaskParams = ({ userId, taskId }) => ({
TableName: process.env.DYNAMODB_TASKS_TABLE,
Key: { userId, taskId },
});

module.exports = {
createTaskParams,
getTasksParams,
updateTaskParams,
deleteTaskParams,
};
Loading

0 comments on commit c636835

Please sign in to comment.