Dgraph-js-extras a helper library for dgraph-js

So, I have a helper library I have been writting to drive my NodeJS app.

It’s jus a collection of functions that use dgraph-js. It has no dependencies other than the peer dependencies of dgraph-js and grpc.

One sample function it has is an upsert function that let’s you upsert in one line.

const updateJunior = {
    skill: 'Javascript',
    level: 10,
    x: 'y',
    y: 'y',
    z: 'y'
};

// If you already had a node in the db that looks like:
const existingNode = {
    skill: 'Javascript',
    level: 10,
    x: 'foo',
    y: 'foo',
    z: 'foo'
};

// You can pass an array of values to update, or just an object.
const updates = [updateJunior];

// The basicEqualityUpsertFn below will find any nodes that has both skill and level predicates.
const upsertFn = basicEqualityUpsertFn(['skill', 'level']);

// x, y and z will be updated from 'foo' to 'y', because both skill and level match.

// If no node matched both skill 'Javascript' and level '10' a new node would be created.
// We can await this direclty as it includes commit and txn postfix. 
const [uid] = await xUpsertCommitTxn(upsertFn, updates, dgraphClient);

// It returns the uids of the found or created nodes.
// If you want it as part of a bigger transaction there is also a xUpsertObject function you could use.

You can also compose some of the functions together.

 const users = [
    { username: 'foo' }
    { username: 'bar' }
 ]
 
 const [id1, id2] = await xExtractUids(xSetJSONCommitTxn(users, dgraphClient));

xSetJSONCommitTxn is just shorthand for

const mu = new _dgraph.Mutation();
mu.setSetJson(object);
mu.setCommitNow(true);
return dgraphClient.newTxn().mutate(mu);

But you can wrap it in xExtractUids to quickly get back the ids if you need to then use them elsewhere.

Hopefully someone finds this useful!
Let me know what you think.

I have documented it but it might be a bit rough will go through next week and try to tweak / improve it a bit with some fresh eyes.

1 Like

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.