Skip to content

Commit 24bae56

Browse files
author
Chris Cho
authored
DOCSP-7589: Update NodeJS examples in CSFLE to be more idiomatic (#569)
* DOCSP-7589 update NodeJS examples to be more idiomatic and use async await syntax
1 parent 41b8bad commit 24bae56

File tree

4 files changed

+75
-90
lines changed

4 files changed

+75
-90
lines changed

source/includes/steps-fle-configure-the-mongodb-client.yaml

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ content: |
1818
1919
.. code-block:: javascript
2020
21-
const keyVaultNamespace = "encryption.__keyVault";
21+
const keyVaultNamespace = 'encryption.__keyVault';
2222
.. tab::
2323
:tabid: python
2424
@@ -96,7 +96,7 @@ content: |
9696
:emphasize-lines: 2
9797
9898
const patientSchema = {
99-
"medicalRecords.patients": jsonSchema,
99+
'medicalRecords.patients': jsonSchema,
100100
}
101101
.. tab::
102102
:tabid: python
@@ -146,7 +146,7 @@ content: |
146146
:emphasize-lines: 2
147147
148148
const extraOptions = {
149-
mongocryptdSpawnPath: "/usr/local/bin/mongocryptd",
149+
mongocryptdSpawnPath: '/usr/local/bin/mongocryptd',
150150
}
151151
152152
.. admonition:: Encryption Binary Daemon

source/includes/steps-fle-convert-to-a-remote-master-key.yaml

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -64,10 +64,10 @@ content: |
6464
.. code-block:: javascript
6565
6666
kmsProviders = {
67-
aws: {
68-
accessKeyId: "<IAM User Access Key ID>",
69-
secretAccessKey: "<IAM User Secret Access Key>",
70-
}
67+
aws: {
68+
accessKeyId: '<IAM User Access Key ID>',
69+
secretAccessKey: '<IAM User Secret Access Key>',
70+
}
7171
}
7272
.. tab::
7373
:tabid: python
@@ -127,18 +127,18 @@ content: |
127127
.. code-block:: javascript
128128
129129
const encryption = new ClientEncryption(client, {
130-
keyVaultNamespace,
131-
kmsProviders
130+
keyVaultNamespace,
131+
kmsProviders
132132
});
133-
encryption.createDataKey("aws", {
133+
const key = await encryption.createDataKey('aws', {
134134
masterKey: {
135-
key: "<Master Key ARN>", // e.g. "arn:aws:kms:us-east-2:111122223333:alias/test-key"
136-
region: "<Master Key AWS Region>", // e.g. "us-east-1"
135+
key: '<Master Key ARN>', // e.g. 'arn:aws:kms:us-east-2:111122223333:alias/test-key'
136+
region: '<Master Key AWS Region>', // e.g. 'us-east-1'
137137
}
138-
}, (err, key) => {
139-
const base64DataKeyId = key.toString('base64');
140-
console.log("DataKeyId [base64]: ", base64DataKeyId);
141138
});
139+
140+
const base64DataKeyId = key.toString('base64');
141+
console.log('DataKeyId [base64]: ', base64DataKeyId);
142142
.. tab::
143143
:tabid: python
144144

source/includes/steps-fle-create-data-encryption-key.yaml

Lines changed: 35 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -28,14 +28,10 @@ content: |
2828
:tabid: nodejs
2929
3030
.. code-block:: javascript
31-
:emphasize-lines: 5
31+
:emphasize-lines: 2
3232
33-
const path = "./master-key.txt";
34-
let localMasterKey;
35-
fs.readFile(path, (err, data) => {
36-
if (err) throw err;
37-
localMasterKey = data;
38-
});
33+
const path = './master-key.txt';
34+
const localMasterKey = fs.readFileSync(path);
3935
.. tab::
4036
:tabid: python
4137
@@ -141,36 +137,34 @@ content: |
141137
:tabid: nodejs
142138
143139
.. code-block:: javascript
144-
:emphasize-lines: 10,11,13,14,16
140+
:emphasize-lines: 12,14,15,17
145141
146-
const base64 = require("uuid-base64");
142+
const base64 = require('uuid-base64');
147143
148-
const connectionString = "mongodb://localhost:27017";
149-
const keyVaultNamespace = "encryption.__keyVault";
144+
const connectionString = 'mongodb://localhost:27017';
145+
const keyVaultNamespace = 'encryption.__keyVault';
150146
const client = new MongoClient(connectionString, {
151147
useNewUrlParser: true,
152148
useUnifiedTopology: true,
153149
});
154150
155-
client.connect()
156-
.then((clientConnection) => {
151+
async function main() {
152+
try {
153+
await client.connect();
157154
const encryption = new ClientEncryption(client, {
158155
keyVaultNamespace,
159156
kmsProviders,
160157
});
161-
encryption.createDataKey("local", (err, key) => {
162-
if (err) {
163-
console.error(err);
164-
} else {
165-
const base64DataKeyId = key.toString("base64");
166-
const uuidDataKeyId = base64.decode(base64DataKeyId);
167-
console.log("DataKeyId [UUID]: ", uuidDataKeyId);
168-
console.log("DataKeyId [base64]: ", base64DataKeyId);
169-
}
170-
});
171-
// ...
172-
});
173-
158+
const key = await encryption.createDataKey('local');
159+
const base64DataKeyId = key.toString('base64');
160+
const uuidDataKeyId = base64.decode(base64DataKeyId);
161+
console.log('DataKeyId [UUID]: ', uuidDataKeyId);
162+
console.log('DataKeyId [base64]: ', base64DataKeyId);
163+
} finally {
164+
await client.close();
165+
}
166+
}
167+
main();
174168
175169
.. note::
176170
@@ -302,28 +296,31 @@ content: |
302296
.. code-block:: javascript
303297
:emphasize-lines: 4
304298
305-
const connectionString = "mongodb://localhost:27017/";
306-
const keyVaultDb = "encryption";
307-
const keyVaultCollection = "__keyVault";
308-
const base64KeyId = "3k13WkSZSLy7kwAAP4HDyQ=="; // use the base64 data key id returned by createKey() in the prior step
299+
const connectionString = 'mongodb://localhost:27017/';
300+
const keyVaultDb = 'encryption';
301+
const keyVaultCollection = '__keyVault';
302+
const base64KeyId = '3k13WkSZSLy7kwAAP4HDyQ=='; // use the base64 data key id returned by createKey() in the prior step
309303
310304
const client = new MongoClient(connectionString, {
311305
useNewUrlParser: true,
312306
useUnifiedTopology: true,
313307
});
314308
315-
client.connect()
316-
.then((clientConnection) => {
317-
const keyDB = clientConnection.db(keyVaultDb);
309+
async function main() {
310+
try {
311+
await client.connect();
312+
const keyDB = client.db(keyVaultDb);
318313
const keyColl = keyDB.collection(keyVaultCollection);
319314
const query = {
320315
_id: base64KeyId,
321316
};
322-
keyColl.findOne(query)
323-
.then((dataKey) => {
324-
console.log(dataKey);
325-
});
326-
});
317+
const dataKey = await keyColl.findOne(query);
318+
console.log(dataKey);
319+
} finally {
320+
await client.close();
321+
}
322+
}
323+
main();
327324
328325
This code example should print a retrieved document that resembles the
329326
following:

source/use-cases/client-side-field-level-encryption-guide.txt

Lines changed: 25 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -196,10 +196,6 @@ Additional Dependencies
196196
<https://www.npmjs.com/package/mongodb-client-encryption>`_
197197
- NodeJS wrapper for the ``libmongocrypt`` encryption library.
198198

199-
* - `secure-random
200-
<https://www.npmjs.com/package/secure-random#nodejsbrowserify>`_
201-
- Generate cryptographically strong random values.
202-
203199
* - `uuid-base64
204200
<https://www.npmjs.com/package/uuid-base64#installation>`_
205201
- Convert between Base64 and hexadecimal UUIDs.
@@ -276,27 +272,21 @@ To begin development, MedcoMD engineers generate a locally-managed master key:
276272

277273
.. code-block:: javascript
278274

279-
const fs = require("fs");
280-
const secureRandom = require("secure-random");
281-
282-
const wstream = fs.createWriteStream("master-key.txt");
283-
const data = secureRandom.randomUint8Array(96);
284-
wstream.write(data);
285-
wstream.end();
275+
const fs = require('fs');
276+
const crypto = require('crypto');
286277

287-
.. note::
288-
289-
This code includes a dependency on the ``secure-random``
290-
npm package. See the `npmjs documentation on the secure-random
291-
package <https://www.npmjs.com/package/secure-random>`_ for
292-
installation instructions.
278+
try {
279+
fs.writeFileSync('master-key.txt', crypto.randomBytes(96));
280+
} catch (err) {
281+
console.error(err);
282+
}
293283
.. tab::
294284
:tabid: python
295285

296286
The following script generates a 96-byte locally-managed master key and
297287
saves it to a file called ``master-key.txt`` in the directory
298288
from which the script is executed.
299-
289+
300290
.. code-block:: python
301291

302292
import os
@@ -344,10 +334,10 @@ locally-managed master key.
344334
<https://raw.githubusercontent.com/mongodb/docs-assets/DOCSP-csfle-data-encryption-key/DataEncryptionKeyGenerator.js>`_.
345335

346336
.. note::
347-
337+
348338
The code linked above includes a dependency on the
349339
``mongo-client-encryption`` npm package. See the `npmjs
350-
documentation on the mongodb-client-encryption package
340+
documentation on the mongodb-client-encryption package
351341
<https://www.npmjs.com/package/mongodb-client-encryption>`_ for
352342
installation instructions.
353343
.. tab::
@@ -623,23 +613,21 @@ MedcoMD engineers write a function to create a new patient record:
623613

624614
.. code-block:: javascript
625615

626-
function insertPatient(collection, name, ssn, bloodType, medicalRecords, policyNumber, provider) {
627-
collection.insertOne({
628-
name: name,
629-
ssn: ssn,
630-
bloodType: bloodType,
631-
medicalRecords: medicalRecords,
632-
insurance: {
633-
policyNumber: policyNumber,
634-
provider: provider
635-
}
636-
})
637-
.then((writeResult) => {
638-
console.log("writeResult:", writeResult);
639-
})
640-
.catch((writeError) => {
641-
console.log("writeError occurred:", writeError);
642-
})
616+
async function insertPatient(collection, name, ssn, bloodType, medicalRecords, policyNumber, provider) {
617+
try {
618+
const writeResult = await collection.insertOne({
619+
name,
620+
ssn,
621+
bloodType,
622+
medicalRecords,
623+
insurance: {
624+
policyNumber,
625+
provider
626+
}
627+
});
628+
} catch (writeError) {
629+
console.error('writeError occurred:', writeError);
630+
}
643631
}
644632
.. tab::
645633
:tabid: python

0 commit comments

Comments
 (0)