-
Notifications
You must be signed in to change notification settings - Fork 4
/
Atlas_Triggers_analyzeReviewSentiment_1686394580.js
51 lines (41 loc) · 1.36 KB
/
Atlas_Triggers_analyzeReviewSentiment_1686394580.js
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
const serviceName = "M0";
const databaseName = "sample_restaurants";
const collectionName = "processed_reviews";
// Add the Google Cloud Function URL below
const analyzeSentimentFunctionURL = "<google-cloud-function-endpoint>";
exports = async function(changeEvent) {
const fullDocument = changeEvent?.fullDocument;
const text = fullDocument?.text;
if (!text) {
throw new Error("Review text is required");
}
const response = await context.http.post({
url: analyzeSentimentFunctionURL,
body: { text },
encodeBodyAsJSON: true
});
let analysis;
let parsedResponse;
try {
// The response body is a BSON.Binary object.
analysis = EJSON.parse(response?.body?.text())?.sentiment;
parsedResponse = JSON.parse(analysis);
} catch (error) {
throw new Error("Parsing sentiment analysis failed. " + analysis);
}
if (!parsedResponse) {
throw new Error("Sentiment analysis failed.");
}
if (parsedResponse?.sentiment === "Invalid review" || !parsedResponse?.sentiment) {
throw new Error("Invalid review: ", text);
}
const collection = context?.services?.get(serviceName)?.db(databaseName)?.collection(collectionName);
if (!collection) {
throw new Error("Fetching destination collection failed.");
}
await collection.insertOne({
...fullDocument,
...parsedResponse
});
return parsedResponse;
};