-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapi-condition.js
55 lines (46 loc) · 1.74 KB
/
api-condition.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
52
53
54
55
import { onRequest } from "firebase-functions/v2/https";
import { db } from "./app.js";
import writeLog from "./write-log.js";
import MESSAGES from "./api-messages.js";
export const apiCondition = onRequest({ cors: true }, async (req, res) => {
const { experimentID } = req.body;
if (!experimentID) {
res.status(400).json(MESSAGES.MISSING_PARAMETER);
return;
}
await writeLog(experimentID, "getCondition");
const exp_doc_ref = db.collection("experiments").doc(experimentID);
const exp_doc = await exp_doc_ref.get();
if (!exp_doc.exists) {
res.status(400).json(MESSAGES.EXPERIMENT_NOT_FOUND);
return;
}
const exp_data = exp_doc.data();
if (!exp_data.activeConditionAssignment) {
res.status(400).json(MESSAGES.CONDITION_ASSIGNMENT_NOT_ACTIVE);
return;
}
// if there is only 1 condition, just send 0
if (exp_data.nConditions === 1) {
res.status(200).json({ message: "Success", condition: 0 });
return;
}
// use a transaction here because current SDK doesn't supply transformed result after a set operation.
// this might change in the future because it seems to be supported in other versions of the SDK.
let condition;
try {
condition = await db.runTransaction(async (t) => {
const exp_doc = await t.get(exp_doc_ref);
const exp_data = exp_doc.data();
const currentCondition = exp_data.currentCondition;
const nextCondition = (currentCondition + 1) % exp_data.nConditions;
t.set(exp_doc_ref, { currentCondition: nextCondition }, { merge: true });
return currentCondition;
});
} catch (error) {
res.status(400).json(MESSAGES.UNKNOWN_ERROR_GETTING_CONDITION);
return;
}
res.status(200).json({ message: "Success", condition: condition });
return;
});