Connection
- class Connection()
Represents a signed, permission-checked connection to a Jnu-backed database. Instances are normally obtained via
connect(), not constructed directly –connect()also downloads and attaches the databaseschema, which the constructor by itself doesn’t do.Connectionis anEventEmitter; see Events below for the events it emits.
Constructor
new Connection(serviceName, idKeystore);
Arguments:
serviceName (string) - The service whose database to connect to; must be a key in
dcpConfigwith aservices.jnuentry. Throws if that service has noservices.jnu.location.idKeystore (Keystore|PrivateKey) - An already-resolved (not a Promise)
KeystoreorPrivateKeywhose signature will authenticate every query made through this connection. Throws if its.addressisn’t a validwallet.Address.
Note
Unlike connect(), this constructor does not fetch a schema – connection.schema is undefined until something sets it. Prefer connect() unless you have a specific reason to manage the schema yourself.
Properties
config
- Connection.config
- Type:
object
The services.jnu fragment of dcpConfig[serviceName] this connection was constructed with.
identity
- Connection.identity
- Type:
Keystore|PrivateKey
The identity every query is signed with.
schema
Methods
endpointOf
- endpointOf(method)
Computes the full endpoint URL for a given Jnu method name.
- Arguments:
method (string) – The method name (e.g. ‘select’, ‘add’). Throws if empty or not a string.
- Return type:
string
performQuery
- performQuery(query)
Low-level method that signs query with this connection’s identity and submits it to the server, returning its result, or rejecting if the server responded with an error. The CRUD and query methods below all use this internally – most applications won’t need to call it directly.
- Arguments:
query (object) – A prepared (not yet signed) query object, as returned by
makeQuery().
- Return type:
Promise<object>
Note
Signing happens here, immediately before submission (via the identity’s makeSignedMessageObject, under the hood of a shared submitSignedPost utility) – query itself, as prepared by :meth:makeQuery, is unsigned.
makeQuery
- makeQuery(method, query, options, expiry)
Instance-method shorthand for the module-level jnu.makeQuery() function, using this connection. Prepares (but does not sign) a query object for
performQuery().- Return type:
Promise<object>
Note
For any method other than 'schema', this throws if query is missing a table (or a tables array matched 1:1 with a prototypes array), or is missing a prototype (or prototypes).
serverRelativeTime
- serverRelativeTime(interval, now)
Computes a point in time relative to the Jnu server’s clock rather than the local machine’s, for storing timestamps that need to be comparable across clients with clock skew.
- Arguments:
interval (number) – Offset from “now”, in seconds.
now – Optional. The local Date/timestamp to use as “now”; defaults to the actual current time.
- Return type:
number
Note
Its own source comment claims it “throws if used before schema is loaded”, but that doesn’t match the implementation: it never touches this.schema. What it actually throws on (via a lower-level dcp/utils helper) is having no cached client/server clock-offset measurement yet for this connection’s time service – which, in practice, means calling it before this connection has successfully submitted at least one query.
getPrimaryKeyColumnName
- getPrimaryKeyColumnName(tableName)
Looks up the name of tableName’s primary-key column in this.schema.
- Arguments:
tableName (string)
- Return type:
string
add
- add(query, options)
Inserts a row. This is an async method that returns a Promise.
- Arguments:
query (object) – An ormdb-style query object describing what to insert (see Query Objects, below).
options (object) – Optional. Defaults to { variant: ‘add’ }.
- Return type:
Promise<object>
change
- change(query, options)
Updates row(s) matching query. This is an async method that returns a Promise.
- Arguments:
query (object) – An ormdb-style query object.
options (object) – Optional. Defaults to { variant: ‘change’ }.
- Return type:
Promise<object>
changeOrAdd
changeMany
delete
- delete(query, options)
Deletes row(s) matching query. This is an async method that returns a Promise.
- Arguments:
query (object) – An ormdb-style query object.
options (object) – Optional. Defaults to { variant: ‘delete’ }.
- Return type:
Promise<object>
deleteMany
select
- select(query, options)
Retrieves rows matching query. This is an async method that returns a Promise.
- Arguments:
query (object) – An ormdb-style query object (see Query Objects, below).
options (object) – Optional query variant/shaping options; see
search(),isearch(),count(),groupCount(), and the select* aggregate methods below for the common ones.
- Return type:
Promise<ResultSet|object|number>
Note
The resolved type depends on the response shape: ordinary row-returning queries resolve with a ResultSet(). Aggregate variants (selectSum(), selectMax(), selectMin(), selectAvg()) resolve with the raw scalar value instead, since their response has no rowCount to wrap.
search / isearch
count
- count(query)
- Arguments:
query (object)
- Return type:
Promise<ResultSet|object>
Equivalent to
select()with { variant: ‘count’ }.
Note
count() does not special-case its return value – it delegates straight to select(), same as search/isearch/groupCount/the select* aggregates, and resolves with whatever select() resolves with for a count-variant query.
groupCount
selectSum / selectMax / selectMin / selectAvg
- selectSum(columnName, query)
Equivalent to
select()with { variant: ‘sum’, columnName }. Resolves with the raw scalar sum, not aResultSet().
- selectMax(columnName, query)
As
selectSum(), with variant: ‘max’.
- selectMin(columnName, query)
As
selectSum(), with variant: ‘min’.
- selectAvg(columnName, query)
As
selectSum(), with variant: ‘avg’.
selectDistinct
Query Objects
query arguments above follow the ormdb query model. The exact grammar is beyond the scope of this reference, but commonly used properties include:
table (string) - The table to operate on.
prototype (object) - A partial row used as a match filter (for
select/change/delete) or as the row to insert (foradd).limit / skip (number) - Pagination.
order (string) - Column to sort by.
desc (boolean) - Sort descending instead of ascending.
Events
Connection is an EventEmitter. Handlers are attached the usual way, for example, connection.on('busy', () => { ... }).
busy - emitted immediately before a query is sent to the server (from
performQuery()).unbusy - emitted once that query’s response (success or failure) has been processed.
Note
There is currently no usable error event: the error path in performQuery() calls this.emit(error) – passing the Error instance itself as the event name, rather than this.emit('error', error) – so an ordinary connection.on('error', ...) listener will never see it. Query failures still surface correctly as rejected Promises; only the EventEmitter side-channel is affected.
Example
const jnu = require('dcp/jnu');
const db = await jnu.connect('scheduler');
const jobs = await db.select({
table: 'jobs',
prototype: { owner: myAddress.toString() },
limit: 20,
order: 'startTime',
desc: true,
});
console.log('Found', jobs.rowCount, 'jobs');
await jobs.rows.forEach((job) => console.log(job));
const totalPaid = await db.selectSum('paidOut', {
table: 'jobs',
prototype: { owner: myAddress.toString() },
});
console.log('Total paid out:', totalPaid);