-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgetTasks.js
More file actions
109 lines (95 loc) · 3.2 KB
/
Copy pathgetTasks.js
File metadata and controls
109 lines (95 loc) · 3.2 KB
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
/**
* Lambda Function: GetTasks
* Purpose: Retrieve all tasks for a user from DynamoDB
* Trigger: API Gateway GET /tasks
*/
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb');
const { DynamoDBDocumentClient, QueryCommand } = require('@aws-sdk/lib-dynamodb');
// Initialize DynamoDB client
const client = new DynamoDBClient({});
const docClient = DynamoDBDocumentClient.from(client);
// Table name from environment variable
const TABLE_NAME = process.env.TABLE_NAME || 'TasksTable';
/**
* Main Lambda handler
*/
exports.handler = async (event) => {
console.log('Event received:', JSON.stringify(event, null, 2));
try {
// Extract user ID from Cognito authorizer context
const userId = event.requestContext.authorizer.claims.sub ||
event.requestContext.authorizer.claims['cognito:username'];
if (!userId) {
return createResponse(401, { message: 'Unauthorized: No user ID found' });
}
// Query DynamoDB for user's tasks
const params = {
TableName: TABLE_NAME,
KeyConditionExpression: 'userId = :userId',
ExpressionAttributeValues: {
':userId': userId
},
ScanIndexForward: false // Sort by most recent first
};
const result = await docClient.send(new QueryCommand(params));
console.log(`Found ${result.Items.length} tasks for user ${userId}`);
// Return tasks
return createResponse(200, {
tasks: result.Items || [],
count: result.Items.length
});
} catch (error) {
console.error('Error retrieving tasks:', error);
return createResponse(500, {
message: 'Internal server error',
error: error.message
});
}
};
/**
* Helper function to create API Gateway response
*/
function createResponse(statusCode, body) {
return {
statusCode: statusCode,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*', // Configure based on your domain
'Access-Control-Allow-Headers': 'Content-Type,Authorization',
'Access-Control-Allow-Methods': 'GET,POST,PUT,DELETE,OPTIONS'
},
body: JSON.stringify(body)
};
}
/**
* DEPLOYMENT INSTRUCTIONS:
*
* 1. Create Lambda function in AWS Console
* 2. Set runtime to Node.js 18.x or later
* 3. Add environment variable:
* - Key: TABLE_NAME
* - Value: TasksTable
*
* 4. Update Lambda execution role with DynamoDB permissions:
* {
* "Effect": "Allow",
* "Action": [
* "dynamodb:Query",
* "dynamodb:GetItem"
* ],
* "Resource": "arn:aws:dynamodb:REGION:ACCOUNT_ID:table/TasksTable"
* }
*
* 5. Install dependencies (if using deployment package):
* npm init -y
* npm install @aws-sdk/client-dynamodb @aws-sdk/lib-dynamodb
*
* 6. For Lambda Layer (recommended):
* Create layer with node_modules containing the above packages
*
* 7. Configure API Gateway:
* - Method: GET
* - Resource: /tasks
* - Authorization: Cognito User Pool
* - Enable CORS
*/