Features a DgraphTransaction class that creates a transaction object with lots of features to ease workflow with dgraph cloud instances.
npm install @feelinglovelynow/dgraphbash
pnpm add @feelinglovelynow/dgraph
`
π€ Unit Tests
!Statements
π Description
* B/c the npm package dgraph-js-http has a dependency on jsonwebtoken it does not work on the edge
* @feelinglovelynow/dgraph has 0 dependencies and works on the edge
* Features a DgraphTransaction class that creates a transaction object with lots of features to ease workflow with dgraph cloud instances. Guidance came from here.
* Not officially supported by Dgraph btw, just created to get Dgraph loveliness in Cloudflare Workers! All the features my site uses everyday are included; if there is something you'd love that isn't included, let's chat please!
π Constructor
`ts
constructor ({ apiKey, endpoint, readOnly, bestEffort, timeout })
`
* apiKey { string }: Required: Found @ Dgraph Cloud > Settings > Api Keys
* endpoint { string }: Required: Found @ Dgraph Cloud > GraphQL Endpoint. Remove /graphql from endpoint b4 sending to this constructor
* readOnly { boolean }: Default is false: Read only transactions are useful to increase read speed because they can circumvent the usual consensus protocol. Read-only transactions cannot contain mutations.
* bestEffort { boolean }: Default is false: The bestEffort flag asks Dgraph Alpha to try to get timestamps from memory on a best-effort basis to reduce the number of outbound requests to Zero. This may yield improved latencies in read-bound workloads where linearizable reads are not strictly needed.
* timeout { number }: Default is 600: Max seconds any query of this transaction will be allowed to be attempted
π Mutations
* transaction.mutate({ mutation, remove, commitNow }: DgraphMutationOptions): Promise
* Mutate dgraph cloud instance.
* Only accepts rdf triples syntax
* If commitNow is true we send commitNow=true in this mutation api calls query param AND set this.#isCommited = true
`ts
const t1 = new DgraphTransaction({ ...txnOptions() })await t1.mutate({ // remove + commit t1
commitNow: true,
remove:
<${ uid }> .
})const t2 = new DgraphTransaction({ ...txnOptions() })
await t2.mutate({ // mutation
mutation:
})await t2.mutate({ remove:
<${ uid5 }> . }) // removeawait t2.commit() // commit t2
`π§‘ Query
* transaction.query(closeWhenDone: boolean, query: string): Promise
* Query dgraph cloud instance
* Only accepts DQL syntax
* IF closeWhenDone is true the transaction will not be allowed to be used again (does not send a request to dgraph cloud instance, just sets this.#isClosed to true)
`ts
async function getProducts (): Promise {
const transaction = new DgraphTransaction({ ...txnOptions(), readOnly: true, bestEffort: true }) const r = await transaction.query(true,
) return r?.data?.products as Product[]
}
`
β€οΈ Example: txnOptions()
* PUBLIC_ENVIRONMENT is set via @feelinglovelynow/env-write
* All other variables like DGRAPH_CLOUD_API_KEY are in the .env file
`ts
import { PUBLIC_ENVIRONMENT } from '$env/static/public'
import { DGRAPH_CLOUD_URL, DGRAPH_CLOUD_API_KEY, DGRAPH_CLOUD_URL_QA, DGRAPH_CLOUD_API_KEY_QA } from '$env/static/private'
export default function txnOptions (pointMain?: boolean): { endpoint: string, apiKey: string } {
return pointMain || PUBLIC_ENVIRONMENT === 'main' ?
{ endpoint: DGRAPH_CLOUD_URL, apiKey: DGRAPH_CLOUD_API_KEY } :
{ endpoint: DGRAPH_CLOUD_URL_QA, apiKey: DGRAPH_CLOUD_API_KEY_QA }
}
`
π TYPE: DgraphResponse
* transaction.query(closeWhenDone: boolean, query: string): Promise
* transaction.mutate({ mutation, remove, commitNow }: DgraphMutationOptions): Promise
* transaction.commit(): Promise
* transaction.abort(): Promise
`ts
/* @typedef { DgraphQueryResponse | DgraphMutationResponse | DgraphCommitResponse | DgraphAbortResponse | DgraphErrorResponse } DgraphResponse //**
* @typedef { Object } DgraphQueryResponse
* @prop { any } data
* @prop { { txn: DgraphExtensionsTxn } } extensions
* @prop { never= } name
* @prop { never= } url
* @prop { never= } errors
* @prop { never= } code
* @prop { never= } message
*/
/**
* @typedef { Object } DgraphMutationResponse
* @prop { { code: string, message: string, queries: any, uids: any } } data
* @prop { { txn: DgraphExtensionsTxn } } extensions
* @prop { never= } name
* @prop { never= } url
* @prop { never= } errors
* @prop { never= } code
* @prop { never= } message
*/
/**
* @typedef { Object } DgraphCommitResponse
* @prop { { code: string, message: string } } data
* @prop { { txn: DgraphExtensionsTxn } } extensions
* @prop { never= } name
* @prop { never= } url
* @prop { never= } errors
* @prop { never= } code
* @prop { never= } message
*/
/**
* @typedef { Object } DgraphAbortResponse
* @prop { never= } data
* @prop { never= } extensions
* @prop { never= } name
* @prop { never= } url
* @prop { never= } errors
* @prop { string } code
* @prop { string } message
* @prop { never= } code
* @prop { never= } message
*/
/**
* @typedef { Object } DgraphErrorResponse
* @prop { never= } data
* @prop { never= } extensions
* @prop { string } name
* @prop { string } url
* @prop { { message: string, extensions: { code: string } }[] } errors
* @prop { never= } code
* @prop { never= } message
*/
`π TYPE: DgraphMutationOptions
* transaction.mutate({ mutation, remove, commitNow }: DgraphMutationOptions): Promise
`ts
/* @typedef { DgraphMutation | DgraphRemove } DgraphMutationOptions //**
* @typedef DgraphMutation
* @prop { boolean= } commitNow - If
commitNow is true we send query param to dgraph cloud instance in this mutation api call that this is the last query or mutation coming from this transation
* @prop { string } mutation - Only accepts rdf triples syntax
* @prop { never= } remove
*//**
* @typedef DgraphRemove
* @prop { boolean= } commitNow - If
commitNow is true we send query param to dgraph cloud instance in this mutation api call that this is the last query or mutation coming from this transation
* @prop { never= } mutation
* @prop { string } remove - Only accepts rdf triples syntax
*/
`π TYPE: DgraphExtensionsTxn
* In the Response from dgraph cloud instance { data: any, extensions: { txn: DgraphExtensionsTxn } }
`ts
/**
* @typedef { Object } DgraphExtensionsTxn
* @prop { number } start_ts - Start timestamp that uniquely identifies a transaction and doesnβt change over the transaction lifecycle
* @prop { string } hash - Transaction start id like start_ts
* @prop { string[] } [keys] - The set of keys modified by the transaction. Aids in transaction conflict detection. Every mutation sends back a new set of keys. this.#mergeArrays merges the response keys with the existing keys.
* @prop { string[] } [preds] - The set of predicates modified by the transaction. Aids in predicate move detection. Every mutation sends back a new set of preds. this.#mergeArrays merges the response preds with the existing preds.
* @prop { boolean } [readOnly] - Is this a readOnly transaction
* @prop { boolean= } [aborted] - Has this transaction been aborted
*/
`β¨ Abort
* transaction.abort(): Promise
* Abort all mutations that have been done with this transaction
* IF transaction has done any mutations => send an api call to dgraph cloud instance to let it know no more incoming actions will be coming from this transaction and to rollback all that has been done by this transaction
* IF transaction has done no mutations => set this.aborted to true so no further queries or mutations may happen with transaction.
π Commit
* transaction.commit(): Promise
* Commit all mutations that have been done with this transaction
* IF transaction has done any mutations => set this.#isCommited = true AND send a /commit api call to dgraph cloud instance to ask it know to commit this transaction (affirm all transaction's mutations)
* IF transaction has done no mutations => set this.#isCommited = true
π₯ Errors we may throw
* this.query() | this.mutate() | this.abort() | this.commit()
* Basically saying for any of the above functions if the status in not between 200 and 300 we will abort the transaction and throw the error
`ts
try {
const rFetch = await fetch(url, requestInit) if (rFetch.status >= 300) throw rFetch
else return await rFetch.json()
} catch (e) {
await this.abort()
throw e
}
`
* constructor()
`ts
if (!params || typeof params !== 'object') throw { id: 'fln__dgraph__missing-params', message: 'Transaction constructor needs a params object', _errorData: { params } }const { apiKey, endpoint } = params
if (!apiKey) throw { id: 'fln__dgraph__missing-apiKey', message: 'Transaction constructor needs an apiKey', _errorData: { apiKey } }
if (!endpoint) throw { id: 'fln__dgraph__missing-endpoint', message: 'Transaction constructor needs an endpoint', _errorData: { endpoint } }
`
* this.query()
`ts
if (this.#isAborted) throw { id: 'fln__dgraph__already-aborted', message: 'Transaction already aborted', _errorData: { query } }
if (this.#isCommited) throw { id: 'fln__dgraph__already-commited', message: 'Transaction already commited', _errorData: { query } }
if (this.#isClosed) throw { id: 'fln__dgraph__already-closed', message: 'Transaction already closed', _errorData: { query } }
`
* this.mutate()
`ts
if (!params || typeof params !== 'object') throw { id: 'fln__dgraph__missing-params', message: 'Mutate function needs a params object', _errorData: { params } }const { mutation, remove, commitNow } = params
if (!mutation && !remove) throw { id: 'fln__dgraph__empty-mutate', message: 'Mutate function requires a mutation or remove string', _errorData: { mutation, remove } }
if (mutation && remove) throw { id: 'fln__dgraph__full-mutate', message: 'Mutate function requires only a mutation or a remove string but not both' }
if (this.#isAborted) throw { id: 'fln__dgraph__already-aborted', message: 'Transaction already aborted', _errorData: { mutation, remove, commitNow } }
if (this.#isCommited) throw { id: 'fln__dgraph__already-commited', message: 'Transaction already commited', _errorData: { mutation, remove, commitNow } }
if (this.#isClosed) throw { id: 'fln__dgraph__already-closed', message: 'Transaction already closed', _errorData: { mutation, remove, commitNow } }
if (this.#readOnly) throw { id: 'fln__dgraph__readonly-mutation', message: 'Readonly transactions may not contain mutations', _errorData: { mutation, remove, commitNow } }
`
* this.commit()
`ts
if (this.#isAborted) throw { id: 'fln__dgraph__already-aborted', message: 'Transaction already aborted' }
if (this.#isCommited) throw { id: 'fln__dgraph__already-commited', message: 'Transaction already commited' }
if (this.#isClosed) throw { id: 'fln__dgraph__already-closed', message: 'Transaction already closed' }
``