Skip to content

Commit 220c863

Browse files
authored
Add optional commitNow param to dql.mutate. Implement dql.commit. (#44)
Currently, there is no option to utilize the commit endpoint within Lambda functions. As transactions play a crucial role in various Lambda operations, enabling access to the commit endpoint would be advantageous for all Lambda users. The implementation of this feature is straightforward and does not pose a risk of breaking existing Lambda sources. This enhancement would greatly benefit Lambda users by providing a streamlined way to manage transactions within their functions.
1 parent 565d086 commit 220c863

File tree

1 file changed

+30
-2
lines changed

1 file changed

+30
-2
lines changed

src/dgraph.ts

+30-2
Original file line numberDiff line numberDiff line change
@@ -49,15 +49,15 @@ export class dql {
4949
return response.json();
5050
}
5151

52-
async mutate(mutate: string | Object): Promise<GraphQLResponse> {
52+
async mutate(mutate: string | Object, commitNow: boolean = true): Promise<GraphQLResponse> {
5353
const headers: Record<string, string> = { };
5454
headers["Content-Type"] = typeof mutate === 'string' ? "application/rdf" : "application/json"
5555
headers["X-Auth-Token"] = process.env.DGRAPH_TOKEN || "";
5656
// add user access token (login to tenant) if defined
5757
if (this.accessJWT && this.accessJWT!='') {
5858
headers["X-Dgraph-AccessToken"] = this.accessJWT;
5959
}
60-
const response = await fetch(`${process.env.DGRAPH_URL}/mutate?commitNow=true`, {
60+
const response = await fetch(`${process.env.DGRAPH_URL}/mutate?commitNow=${commitNow}`, {
6161
method: "POST",
6262
headers: headers,
6363
body: typeof mutate === 'string' ? mutate : JSON.stringify(mutate)
@@ -68,5 +68,33 @@ export class dql {
6868
return response.json();
6969
}
7070

71+
async commit(txn: {
72+
start_ts: number;
73+
hash: string;
74+
preds: string[];
75+
keys: string[];
76+
}): Promise<GraphQLResponse> {
77+
const headers: Record<string, string> = {};
78+
headers["Content-Type"] = "application/json";
79+
headers["X-Auth-Token"] = process.env.DGRAPH_TOKEN || "";
80+
// add user access token (login to tenant) if defined
81+
if (this.accessJWT && this.accessJWT != "") {
82+
headers["X-Dgraph-AccessToken"] = this.accessJWT;
83+
}
84+
const { start_ts, hash, ...rest } = txn;
85+
const response = await fetch(
86+
`${process.env.DGRAPH_URL}/commit?startTs=${start_ts}&hash=${hash}`,
87+
{
88+
method: "POST",
89+
headers: headers,
90+
body: JSON.stringify(rest),
91+
}
92+
);
93+
if (response.status !== 200) {
94+
throw new Error("Failed to commit transaction");
95+
}
96+
return response.json();
97+
}
98+
7199
}
72100

0 commit comments

Comments
 (0)