-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwordcount-note.js
More file actions
58 lines (48 loc) · 1.88 KB
/
Copy pathwordcount-note.js
File metadata and controls
58 lines (48 loc) · 1.88 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
const AWS = require('aws-sdk');
AWS.config.update({ region: 'us-west-1' });
const _ = require('underscore');
const util = require('./util.js');
const dynamodb = new AWS.DynamoDB.DocumentClient();
const tableName = process.env.NOTES_TABLE;
exports.handler = async (event) => {
try {
//decode function helps to format any encoded special characters and avoid any error regarding the same
let note_id = decodeURIComponent(event.pathParameters.note_id);
// Index note_id is used below which is usually used to optimize the query and the item retrieval
let params = {
TableName: tableName,
IndexName: "note_id-index",
KeyConditionExpression: "note_id = :note_id",
ExpressionAttributeValues: {
":note_id": note_id
},
Limit: 1
};
let data = await dynamodb.query(params).promise();
//This will count all the words in one note's content section
if(!_.isEmpty(data.Items)) {
let noteContent = data.Items[0].content;
let wordCount = noteContent.split(/\s+/).length;
return {
statusCode: 200,
headers: util.getResponseHeaders(),
body: JSON.stringify({ wordCount: wordCount })
};
} else {
return {
statusCode: 404,
headers: util.getResponseHeaders()
};
}
} catch (err) {
console.log("Error", err);
return {
statusCode: err.statusCode ? err.statusCode : 500,
headers: util.getResponseHeaders(),
body: JSON.stringify({
error: err.name ? err.name : "Exception",
message: err.message ? err.message : "Unknown error"
})
};
}
}