Skip to content

Commit fb9579e

Browse files
fix example
1 parent 3638e05 commit fb9579e

File tree

6 files changed

+122
-8
lines changed

6 files changed

+122
-8
lines changed

README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ Using the `open` function with a connection string:
8080

8181
```js
8282
// open a connection to an ACL-enabled, non-TLS cluster and login as groot
83-
const client = dgraph.open("dgraph://groot:password@localhost:8090")
83+
const client = await dgraph.open("dgraph://groot:password@localhost:8090")
8484
// Use the client
8585

8686
// this will close all the client stubs
@@ -381,7 +381,7 @@ const SERVER_ADDR = "localhost:9080"
381381
const SERVER_CREDENTIALS = grpc.credentials.createInsecure()
382382

383383
// Create instances of DgraphClient.
384-
const client = dgraph.open("dgraph://groot:password@${SERVER_ADDR}")
384+
const client = await dgraph.open("dgraph://groot:password@${SERVER_ADDR}")
385385

386386
// ...
387387
// Use dgraphClient

examples/simple/index.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -115,7 +115,7 @@ async function queryData(dgraphClient) {
115115
}
116116

117117
async function main() {
118-
const dgraphClient = dgraph.open()
118+
const dgraphClient = await dgraph.open("dgraph://groot:password@localhost:8090")
119119
await dropAll(dgraphClient)
120120
await setSchema(dgraphClient)
121121
await createData(dgraphClient)

lib/client.d.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,8 @@ export declare class DgraphClient {
2121
setDebugMode(mode?: boolean): void
2222
debug(msg: string): void
2323
anyClient(): DgraphClientStub
24+
close(): void
2425
}
2526
export declare function isJwtExpired(err: any): boolean
2627
export declare function deleteEdges(mu: types.Mutation, uid: string, ...predicates: string[]): void
28+
export declare function open(connStr: string): Promise<DgraphClient>

lib/client.js

Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -141,11 +141,18 @@ Object.defineProperty(exports, "__esModule", { value: true })
141141
exports.DgraphClient = void 0
142142
exports.isJwtExpired = isJwtExpired
143143
exports.deleteEdges = deleteEdges
144+
exports.open = open
145+
var grpc = require("@grpc/grpc-js")
144146
var messages = require("../generated/api_pb")
147+
var clientStub_1 = require("./clientStub")
145148
var errors_1 = require("./errors")
146149
var txn_1 = require("./txn")
147150
var types = require("./types")
148151
var util_1 = require("./util")
152+
var dgraphScheme = "dgraph:"
153+
var sslModeDisable = "disable"
154+
var sslModeRequire = "require"
155+
var sslModeVerifyCA = "verify-ca"
149156
var DgraphClient = (function () {
150157
function DgraphClient() {
151158
var clients = []
@@ -220,6 +227,16 @@ var DgraphClient = (function () {
220227
DgraphClient.prototype.anyClient = function () {
221228
return this.clients[Math.floor(Math.random() * this.clients.length)]
222229
}
230+
DgraphClient.prototype.close = function () {
231+
this.clients.forEach(function (clientStub) {
232+
try {
233+
clientStub.close()
234+
console.log("Closed client stub successfully")
235+
} catch (error) {
236+
console.error("Failed to close client stub:", error)
237+
}
238+
})
239+
}
223240
return DgraphClient
224241
})()
225242
exports.DgraphClient = DgraphClient
@@ -245,3 +262,99 @@ function deleteEdges(mu, uid) {
245262
mu.addDel(nquad)
246263
}
247264
}
265+
function addApiKeyToCredentials(baseCreds, apiKey) {
266+
var metaCreds = grpc.credentials.createFromMetadataGenerator(function (_, callback) {
267+
var metadata = new grpc.Metadata()
268+
metadata.add("authorization", apiKey)
269+
callback(null, metadata)
270+
})
271+
return grpc.credentials.combineChannelCredentials(baseCreds, metaCreds)
272+
}
273+
function addBearerTokenToCredentials(baseCreds, bearerToken) {
274+
var metaCreds = grpc.credentials.createFromMetadataGenerator(function (_, callback) {
275+
var metadata = new grpc.Metadata()
276+
metadata.add("Authorization", "Bearer ".concat(bearerToken))
277+
callback(null, metadata)
278+
})
279+
return grpc.credentials.combineChannelCredentials(baseCreds, metaCreds)
280+
}
281+
function open(connStr) {
282+
return __awaiter(this, void 0, void 0, function () {
283+
var parsedUrl, host, port, queryParams, sslMode, credentials, clientStub, err_1
284+
return __generator(this, function (_a) {
285+
switch (_a.label) {
286+
case 0:
287+
parsedUrl = new URL(connStr)
288+
if (parsedUrl.protocol !== dgraphScheme) {
289+
throw new Error("Invalid scheme: must start with dgraph://")
290+
}
291+
host = parsedUrl.hostname
292+
port = parsedUrl.port
293+
if (!host) {
294+
throw new Error("Invalid connection string: hostname required")
295+
}
296+
if (!port) {
297+
throw new Error("Invalid connection string: port required")
298+
}
299+
queryParams = {}
300+
if (parsedUrl.searchParams) {
301+
parsedUrl.searchParams.forEach(function (value, key) {
302+
queryParams[key] = value
303+
})
304+
}
305+
if (queryParams.apikey && queryParams.bearertoken) {
306+
throw new Error("Both apikey and bearertoken cannot be provided")
307+
}
308+
sslMode = queryParams.sslmode
309+
if (sslMode === undefined) {
310+
sslMode = sslModeDisable
311+
}
312+
switch (sslMode) {
313+
case sslModeDisable:
314+
credentials = grpc.credentials.createInsecure()
315+
break
316+
case sslModeRequire:
317+
credentials = grpc.credentials.createSsl(null, null, null, {
318+
checkServerIdentity: function () {
319+
return undefined
320+
},
321+
})
322+
break
323+
case sslModeVerifyCA:
324+
credentials = grpc.credentials.createSsl()
325+
break
326+
default:
327+
throw new Error(
328+
"Invalid SSL mode: ".concat(
329+
sslMode,
330+
" (must be one of disable, require, verify-ca)",
331+
),
332+
)
333+
}
334+
if (queryParams.apikey) {
335+
credentials = addApiKeyToCredentials(credentials, queryParams.apikey)
336+
} else if (queryParams.bearertoken) {
337+
credentials = addBearerTokenToCredentials(credentials, queryParams.bearertoken)
338+
}
339+
clientStub = new clientStub_1.DgraphClientStub(
340+
"".concat(host, ":").concat(port),
341+
credentials,
342+
)
343+
if (!(parsedUrl.username != "")) return [3, 4]
344+
if (!(parsedUrl.password === "")) return [3, 1]
345+
throw new Error("Invalid connection string: password required when username is provided")
346+
case 1:
347+
_a.trys.push([1, 3, , 4])
348+
return [4, clientStub.login(parsedUrl.username, parsedUrl.password)]
349+
case 2:
350+
_a.sent()
351+
return [3, 4]
352+
case 3:
353+
err_1 = _a.sent()
354+
throw new Error("Failed to sign in user: ".concat(err_1.message))
355+
case 4:
356+
return [2, new DgraphClient(clientStub)]
357+
}
358+
})
359+
})
360+
}

lib/types.d.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,25 +5,25 @@
55

66
import * as messages from "../generated/api_pb"
77
export declare class Payload extends messages.Payload {
8-
getData(): string | Uint8Array
8+
getData(): any
99
getData_asB64(): string
1010
getData_asU8(): Uint8Array
1111
setData(value: any): void
1212
}
1313
export declare function createPayload(oldPayload: messages.Payload): Payload
1414
export declare class Response extends messages.Response {
15-
getJson(): string | Uint8Array
15+
getJson(): any
1616
getJson_asB64(): string
1717
getJson_asU8(): Uint8Array
1818
setJson(value: any): void
1919
}
2020
export declare function createResponse(oldResponse: messages.Response): Response
2121
export declare class Mutation extends messages.Mutation {
22-
getSetJson(): string | Uint8Array
22+
getSetJson(): any
2323
getSetJson_asB64(): string
2424
getSetJson_asU8(): Uint8Array
2525
setSetJson(value: any): void
26-
getDeleteJson(): string | Uint8Array
26+
getDeleteJson(): any
2727
getDeleteJson_asB64(): string
2828
getDeleteJson_asU8(): Uint8Array
2929
setDeleteJson(value: any): void

package.json

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
{
22
"name": "dgraph-js",
33
"version": "24.1.0",
4-
"type": "module",
54
"description": "Official javascript client for Dgraph",
65
"license": "Apache-2.0",
76
"repository": {

0 commit comments

Comments
 (0)