@fluree/fluree-client
Advanced tools
Comparing version 1.0.6 to 1.0.7
@@ -163,2 +163,25 @@ import { IFlureeConfig } from '../interfaces/IFlureeConfig'; | ||
/** | ||
* Creates a new TransactionInstance for deleting subjects by @id in the Fluree database. The TransactionInstance can be used & re-used to build, sign, and send delete transactions to the Fluree instance. | ||
* | ||
* Delete is not an API endpoint in Fluree. This method helps to transform a single or list of subject identifiers (@id) into a where/delete transaction that deletes the subject and all facts about the subject. | ||
* | ||
* Delete assumes that all facts for the provided subjects should be retracted from the database. | ||
* @param id string | string[] - The subject identifier or identifiers to retract from the Fluree instance | ||
* @returns TransactionInstance | ||
* @example | ||
* // Existing data: | ||
* // [ | ||
* // { "@id": "freddy", "name": "Freddy" }, | ||
* // { "@id": "alice", "name": "Alice" } | ||
* // ] | ||
* | ||
* await client.delete("freddy").send(); | ||
* | ||
* // New data state after txn: | ||
* // [ | ||
* // { "@id": "alice", "name": "Alice", "age": 25 } | ||
* // ] | ||
*/ | ||
delete(id: string | string[]): TransactionInstance; | ||
/** | ||
* Creates a new HistoryQueryInstance for querying the history of the Fluree database. The HistoryQueryInstance can be used & re-used to build, sign, and send history queries to the Fluree instance. | ||
@@ -165,0 +188,0 @@ * @param query {IFlureeHistoryQuery} - The history query to send to the Fluree instance |
@@ -21,3 +21,3 @@ "use strict"; | ||
const transactionUtils_1 = require("../utils/transactionUtils"); | ||
const FlureeError_1 = require("./FlureeError"); | ||
const Error_1 = require("./Error"); | ||
const HistoryQueryInstance_1 = require("./HistoryQueryInstance"); | ||
@@ -168,3 +168,3 @@ const QueryInstance_1 = require("./QueryInstance"); | ||
if (!this.connected) { | ||
throw new FlureeError_1.FlureeError('You must connect before querying. Try using .connect().query() instead'); | ||
throw new Error_1.ApplicationError('You must connect before querying. Try using .connect().query() instead', 'CLIENT_ERROR', null); | ||
} | ||
@@ -195,3 +195,3 @@ if (!query.from) { | ||
if (!this.connected) { | ||
throw new FlureeError_1.FlureeError('You must connect before transacting. Try using .connect().transact() instead'); | ||
throw new Error_1.ApplicationError('You must connect before transacting. Try using .connect().transact() instead', 'CLIENT_ERROR', null); | ||
} | ||
@@ -236,11 +236,41 @@ if (!transaction.ledger) { | ||
if (!this.connected) { | ||
throw new FlureeError_1.FlureeError('You must connect before transacting. Try using .connect().transact() instead'); | ||
throw new Error_1.ApplicationError('You must connect before transacting. Try using .connect().transact() instead', 'CLIENT_ERROR', null); | ||
} | ||
const transactionContext = transaction['@context']; | ||
const idAlias = (0, contextHandler_1.findIdAlias)((0, contextHandler_1.mergeContexts)(this.config.defaultContext || {}, transactionContext || {})); | ||
const idAlias = (0, contextHandler_1.findIdAlias)(this.config.defaultContext || {}); | ||
const resultTransaction = (0, transactionUtils_1.handleUpsert)(transaction, idAlias); | ||
resultTransaction.ledger = transaction.ledger || this.config.ledger; | ||
resultTransaction.ledger = this.config.ledger; | ||
return new TransactionInstance_1.TransactionInstance(resultTransaction, this.config); | ||
} | ||
/** | ||
* Creates a new TransactionInstance for deleting subjects by @id in the Fluree database. The TransactionInstance can be used & re-used to build, sign, and send delete transactions to the Fluree instance. | ||
* | ||
* Delete is not an API endpoint in Fluree. This method helps to transform a single or list of subject identifiers (@id) into a where/delete transaction that deletes the subject and all facts about the subject. | ||
* | ||
* Delete assumes that all facts for the provided subjects should be retracted from the database. | ||
* @param id string | string[] - The subject identifier or identifiers to retract from the Fluree instance | ||
* @returns TransactionInstance | ||
* @example | ||
* // Existing data: | ||
* // [ | ||
* // { "@id": "freddy", "name": "Freddy" }, | ||
* // { "@id": "alice", "name": "Alice" } | ||
* // ] | ||
* | ||
* await client.delete("freddy").send(); | ||
* | ||
* // New data state after txn: | ||
* // [ | ||
* // { "@id": "alice", "name": "Alice", "age": 25 } | ||
* // ] | ||
*/ | ||
delete(id) { | ||
if (!this.connected) { | ||
throw new Error_1.ApplicationError('You must connect before transacting. Try using .connect().transact() instead', 'CLIENT_ERROR', null); | ||
} | ||
const idAlias = (0, contextHandler_1.findIdAlias)(this.config.defaultContext || {}); | ||
const resultTransaction = (0, transactionUtils_1.handleDelete)(id, idAlias); | ||
resultTransaction.ledger = this.config.ledger; | ||
return new TransactionInstance_1.TransactionInstance(resultTransaction, this.config); | ||
} | ||
/** | ||
* Creates a new HistoryQueryInstance for querying the history of the Fluree database. The HistoryQueryInstance can be used & re-used to build, sign, and send history queries to the Fluree instance. | ||
@@ -265,3 +295,3 @@ * @param query {IFlureeHistoryQuery} - The history query to send to the Fluree instance | ||
if (!this.connected) { | ||
throw new FlureeError_1.FlureeError('You must connect before querying history. Try using .connect().history() instead'); | ||
throw new Error_1.ApplicationError('You must connect before querying history. Try using .connect().history() instead', 'CLIENT_ERROR', null); | ||
} | ||
@@ -385,3 +415,3 @@ if (!query.from) { | ||
// if (!didKey) { | ||
// throw new FlureeError( | ||
// throw new ApplicationError( | ||
// 'did is required; try calling generateKeyPair() or passing a did string as a parameter' | ||
@@ -474,3 +504,3 @@ // ); | ||
if (create) { | ||
throw new FlureeError_1.FlureeError('cannot create a ledger through the Fluree hosted service API'); | ||
throw new Error_1.ApplicationError('cannot create a ledger through the Fluree hosted service API', 'CLIENT_ERROR', null); | ||
} | ||
@@ -480,18 +510,18 @@ } | ||
if (!host) { | ||
throw new FlureeError_1.FlureeError('host is required on either FlureeClient or connect'); | ||
throw new Error_1.ApplicationError('host is required on either FlureeClient or connect', 'CLIENT_ERROR', null); | ||
} | ||
} | ||
if (!ledger) { | ||
throw new FlureeError_1.FlureeError('ledger is required on either FlureeClient or connect'); | ||
throw new Error_1.ApplicationError('ledger is required on either FlureeClient or connect', 'CLIENT_ERROR', null); | ||
} | ||
} | ||
if (signMessages && !privateKey) { | ||
throw new FlureeError_1.FlureeError('privateKey is required when signMessages is true'); | ||
throw new Error_1.ApplicationError('privateKey is required when signMessages is true', 'CLIENT_ERROR', null); | ||
} | ||
if (isFlureeHosted) { | ||
if (host) { | ||
throw new FlureeError_1.FlureeError('"host" should not be set when using the Fluree hosted service'); | ||
throw new Error_1.ApplicationError('"host" should not be set when using the Fluree hosted service', 'CLIENT_ERROR', null); | ||
} | ||
if (port) { | ||
throw new FlureeError_1.FlureeError('"port" should not be set when using the Fluree hosted service'); | ||
throw new Error_1.ApplicationError('"port" should not be set when using the Fluree hosted service', 'CLIENT_ERROR', null); | ||
} | ||
@@ -504,12 +534,14 @@ if (!apiKey && !privateKey) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
return this.query({ | ||
const queryInstance = this.query({ | ||
where: { | ||
'@id': '?s', | ||
'?p': '?o', | ||
}, | ||
selectOne: ['?s'], | ||
}).send(); | ||
}); | ||
return queryInstance.send(); | ||
}); | ||
}, _FlureeClient_createLedger = function _FlureeClient_createLedger(ledgerName) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const { host, port } = this.config; | ||
const { host, port, signMessages, privateKey } = this.config; | ||
let url = `http://${host}`; | ||
@@ -520,12 +552,19 @@ if (port) { | ||
url += '/fluree/create'; | ||
const body = JSON.stringify({ | ||
let body = JSON.stringify({ | ||
ledger: ledgerName || this.config.ledger, | ||
insert: { message: 'success' }, | ||
}); | ||
let headers = { | ||
'Content-Type': 'application/json', | ||
}; | ||
if (signMessages && privateKey) { | ||
body = (0, crypto_1.createJWS)(body, privateKey); | ||
headers = { | ||
'Content-Type': 'application/jwt', | ||
}; | ||
} | ||
return fetch(url, { | ||
method: 'POST', | ||
body, | ||
headers: { | ||
'Content-Type': 'application/json', | ||
}, | ||
headers, | ||
}) | ||
@@ -537,3 +576,3 @@ .then((response) => { | ||
if (json.error) { | ||
throw new FlureeError_1.FlureeError(`${json.error}: ${json.message}`); | ||
throw new Error_1.ApplicationError(json.message, json.error || 'CLIENT_ERROR', json); | ||
} | ||
@@ -540,0 +579,0 @@ return json; |
export declare class FlureeError extends Error { | ||
readonly code?: number | undefined; | ||
constructor(message: string, code?: number | undefined); | ||
statusCode?: number | undefined; | ||
statusText?: string | undefined; | ||
originalError?: any; | ||
constructor(message: string, statusCode?: number | undefined, statusText?: string | undefined, originalError?: any); | ||
} |
@@ -5,5 +5,9 @@ "use strict"; | ||
class FlureeError extends Error { | ||
constructor(message, code) { | ||
constructor(message, statusCode, statusText, | ||
// eslint-disable-next-line @typescript-eslint/no-explicit-any | ||
originalError) { | ||
super(message); | ||
this.code = code; | ||
this.statusCode = statusCode; | ||
this.statusText = statusText; | ||
this.originalError = originalError; | ||
this.name = 'FlureeError'; | ||
@@ -10,0 +14,0 @@ if (Error.captureStackTrace) { |
@@ -23,2 +23,3 @@ import { IFlureeConfig } from '../interfaces/IFlureeConfig'; | ||
config: IFlureeConfig; | ||
signedQuery: string; | ||
constructor(query: IFlureeHistoryQuery, config: IFlureeConfig); | ||
@@ -32,2 +33,48 @@ /** | ||
send(): Promise<any>; | ||
/** | ||
* Signs the history query with the provided privateKey (or the privateKey from the config if none is provided) | ||
* @param privateKey - (Optional) The private key to sign the history query with | ||
* @returns HistoryQueryInstance | ||
* @example | ||
* const signedHistoryQuery = historyQuery.sign(privateKey); | ||
* | ||
* // or | ||
* | ||
* const signedHistoryQuery = historyQuery.sign(); // if the privateKey is provided in the config | ||
*/ | ||
sign(privateKey?: string): HistoryQueryInstance; | ||
/** | ||
* Returns the signed history query as a JWS string (if the history query has been signed) | ||
* @returns string | ||
* @example | ||
* const signedHistoryQuery = historyQuery.sign(); | ||
* | ||
* const jwsString = historyQuery.getSignedQuery(); | ||
*/ | ||
getSignedQuery(): string; | ||
/** | ||
* Returns the fully-qualified history query object | ||
* @returns IFlureeHistoryQuery | ||
* @example | ||
* const client = await new FlureeClient({ | ||
* host: localhost, | ||
* port: 8080, | ||
* ledger: 'test/history-query', | ||
* }).connect(); | ||
* | ||
* const historyQuery = client | ||
* .history({ | ||
* 'commit-details': true, | ||
* t: { at: 'latest' }, | ||
* }) | ||
* const historyQueryObject = historyQuery.getQuery(); | ||
* | ||
* console.log(historyQueryObject); | ||
* // { | ||
* // 'commit-details': true, | ||
* // t: { at: 'latest' }, | ||
* // from: "test/history-query" | ||
* // } | ||
*/ | ||
getQuery(): IFlureeHistoryQuery; | ||
} |
@@ -13,4 +13,5 @@ "use strict"; | ||
exports.HistoryQueryInstance = void 0; | ||
const crypto_1 = require("@fluree/crypto"); | ||
const fetchOptions_1 = require("../utils/fetchOptions"); | ||
const FlureeError_1 = require("./FlureeError"); | ||
const Error_1 = require("./Error"); | ||
/** | ||
@@ -35,7 +36,11 @@ * Class representing a history query instance. | ||
constructor(query, config) { | ||
this.signedQuery = ''; | ||
if (!query.history && !query['commit-details']) { | ||
throw new FlureeError_1.FlureeError('either the history or commit-details key is required'); | ||
throw new Error_1.ApplicationError('either the history or commit-details key is required', 'SYNTAX_ERROR', query); | ||
} | ||
this.query = query; | ||
this.config = config; | ||
if (config.signMessages) { | ||
this.sign(); | ||
} | ||
} | ||
@@ -50,9 +55,12 @@ /** | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const [url, fetchOptions] = (0, fetchOptions_1.generateFetchParams)(this.config, 'history'); | ||
fetchOptions.body = JSON.stringify(this.query); | ||
const contentType = this.signedQuery | ||
? 'application/jwt' | ||
: 'application/json'; | ||
const [url, fetchOptions] = (0, fetchOptions_1.generateFetchParams)(this.config, 'history', contentType); | ||
fetchOptions.body = this.signedQuery || JSON.stringify(this.query); | ||
return fetch(url, fetchOptions) | ||
.then((response) => { | ||
// if (response.status > 201) { | ||
// throw new Error(response.statusText); | ||
// } | ||
if (response.status > 201) { | ||
throw new Error_1.HttpError('HTTP Error', response.status, response.statusText); | ||
} | ||
return response.json(); | ||
@@ -62,3 +70,3 @@ }) | ||
if (json.error) { | ||
throw new FlureeError_1.FlureeError(`${json.error}: ${json.message}`); | ||
throw new Error_1.ApplicationError(json.message || 'Application Error', json.error, json); | ||
} | ||
@@ -69,3 +77,65 @@ return json; | ||
} | ||
/** | ||
* Signs the history query with the provided privateKey (or the privateKey from the config if none is provided) | ||
* @param privateKey - (Optional) The private key to sign the history query with | ||
* @returns HistoryQueryInstance | ||
* @example | ||
* const signedHistoryQuery = historyQuery.sign(privateKey); | ||
* | ||
* // or | ||
* | ||
* const signedHistoryQuery = historyQuery.sign(); // if the privateKey is provided in the config | ||
*/ | ||
sign(privateKey) { | ||
const key = privateKey !== null && privateKey !== void 0 ? privateKey : this.config.privateKey; | ||
if (!key) { | ||
throw new Error_1.ApplicationError('privateKey must be provided as either a function parameter or in the config', 'PRIVATE_KEY', null); | ||
} | ||
const signedHistoryQuery = (0, crypto_1.createJWS)(JSON.stringify(this.query), key); | ||
this.signedQuery = signedHistoryQuery; | ||
return this; | ||
} | ||
// setTime(time: string): QueryInstance { | ||
// this.query.t = time; | ||
// return this; | ||
// } | ||
/** | ||
* Returns the signed history query as a JWS string (if the history query has been signed) | ||
* @returns string | ||
* @example | ||
* const signedHistoryQuery = historyQuery.sign(); | ||
* | ||
* const jwsString = historyQuery.getSignedQuery(); | ||
*/ | ||
getSignedQuery() { | ||
return this.signedQuery; | ||
} | ||
/** | ||
* Returns the fully-qualified history query object | ||
* @returns IFlureeHistoryQuery | ||
* @example | ||
* const client = await new FlureeClient({ | ||
* host: localhost, | ||
* port: 8080, | ||
* ledger: 'test/history-query', | ||
* }).connect(); | ||
* | ||
* const historyQuery = client | ||
* .history({ | ||
* 'commit-details': true, | ||
* t: { at: 'latest' }, | ||
* }) | ||
* const historyQueryObject = historyQuery.getQuery(); | ||
* | ||
* console.log(historyQueryObject); | ||
* // { | ||
* // 'commit-details': true, | ||
* // t: { at: 'latest' }, | ||
* // from: "test/history-query" | ||
* // } | ||
*/ | ||
getQuery() { | ||
return this.query; | ||
} | ||
} | ||
exports.HistoryQueryInstance = HistoryQueryInstance; |
@@ -15,4 +15,4 @@ "use strict"; | ||
const fetchOptions_1 = require("../utils/fetchOptions"); | ||
const FlureeError_1 = require("./FlureeError"); | ||
const crypto_1 = require("@fluree/crypto"); | ||
const Error_1 = require("./Error"); | ||
/** | ||
@@ -56,18 +56,33 @@ * Class representing a query instance. | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const query = this.signedQuery || JSON.stringify(this.query); | ||
const [url, fetchOptions] = (0, fetchOptions_1.generateFetchParams)(this.config, 'query'); | ||
fetchOptions.body = query; | ||
return fetch(url, fetchOptions) | ||
.then((response) => { | ||
// if (response.status > 201) { | ||
// throw new Error(response.statusText); | ||
// } | ||
return response.json(); | ||
}) | ||
.then((json) => { | ||
const contentType = this.signedQuery | ||
? 'application/jwt' | ||
: 'application/json'; | ||
const [url, fetchOptions] = (0, fetchOptions_1.generateFetchParams)(this.config, 'query', contentType); | ||
fetchOptions.body = this.signedQuery || JSON.stringify(this.query); | ||
try { | ||
const response = yield fetch(url, fetchOptions); | ||
const json = yield response.json(); | ||
// Check for HTTP errors or application-specific errors in the JSON | ||
if (response.status > 201) { | ||
throw new Error_1.HttpError('HTTP Error', response.status, json); | ||
} | ||
if (json.error) { | ||
throw new FlureeError_1.FlureeError(`${json.error}: ${json.message}`); | ||
throw new Error_1.ApplicationError(json.message || 'Application Error', json.error, json); | ||
} | ||
return json; | ||
}); | ||
} | ||
catch (error) { | ||
if (error instanceof Error_1.HttpError) { | ||
console.error(`HTTP Error: ${error.status}`); | ||
console.error('Response Body: ', JSON.stringify(error.body, null, 2)); | ||
} | ||
else if (error instanceof Error_1.ApplicationError) { | ||
console.error(`Application Error: ${error.errorCode}`); | ||
console.error('Details: ', JSON.stringify(error.details, null, 2)); | ||
} | ||
else { | ||
console.error('Unexpected error: ', error); | ||
} | ||
throw error; | ||
} | ||
}); | ||
@@ -89,5 +104,5 @@ } | ||
if (!key) { | ||
throw new FlureeError_1.FlureeError('privateKey must be provided in either the query or the config'); | ||
throw new Error_1.ApplicationError('privateKey must be provided in either the query or the config', 'NO_PRIVATE_KEY', null); | ||
} | ||
const signedQuery = JSON.stringify((0, crypto_1.createJWS)(JSON.stringify(this.query), key)); | ||
const signedQuery = (0, crypto_1.createJWS)(JSON.stringify(this.query), key); | ||
this.signedQuery = signedQuery; | ||
@@ -94,0 +109,0 @@ return this; |
@@ -15,4 +15,4 @@ "use strict"; | ||
const fetchOptions_1 = require("../utils/fetchOptions"); | ||
const FlureeError_1 = require("./FlureeError"); | ||
const crypto_1 = require("@fluree/crypto"); | ||
const Error_1 = require("./Error"); | ||
/** | ||
@@ -56,18 +56,34 @@ * Class representing a transaction instance. | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const transaction = this.signedTransaction || JSON.stringify(this.transaction); | ||
const [url, fetchOptions] = (0, fetchOptions_1.generateFetchParams)(this.config, 'transact'); | ||
fetchOptions.body = transaction; | ||
return fetch(url, fetchOptions) | ||
.then((response) => { | ||
// if (response.status > 201) { | ||
// throw new Error(response.statusText); | ||
// } | ||
return response.json(); | ||
}) | ||
.then((json) => { | ||
const contentType = this.signedTransaction | ||
? 'application/jwt' | ||
: 'application/json'; | ||
const [url, fetchOptions] = (0, fetchOptions_1.generateFetchParams)(this.config, 'transact', contentType); | ||
fetchOptions.body = | ||
this.signedTransaction || JSON.stringify(this.transaction); | ||
try { | ||
const response = yield fetch(url, fetchOptions); | ||
const json = yield response.json(); | ||
// Check for HTTP errors or application-specific errors in the JSON | ||
if (response.status > 201) { | ||
throw new Error_1.HttpError('HTTP Error', response.status, json); | ||
} | ||
if (json.error) { | ||
throw new Error(`${json.error}: ${json.message}`); | ||
throw new Error_1.ApplicationError(json.message || 'Application Error', json.error, json); | ||
} | ||
return json; | ||
}); | ||
} | ||
catch (error) { | ||
if (error instanceof Error_1.HttpError) { | ||
console.error(`HTTP Error: ${error.status}`); | ||
console.error('Response Body: ', JSON.stringify(error.body, null, 2)); | ||
} | ||
else if (error instanceof Error_1.ApplicationError) { | ||
console.error(`Application Error: ${error.errorCode}`); | ||
console.error('Details: ', JSON.stringify(error.details, null, 2)); | ||
} | ||
else { | ||
console.error('Unexpected error: ', error); | ||
} | ||
throw error; | ||
} | ||
}); | ||
@@ -89,5 +105,5 @@ } | ||
if (!key) { | ||
throw new FlureeError_1.FlureeError('privateKey must be provided in either the query or the config'); | ||
throw new Error_1.ApplicationError('privateKey must be provided in either the transaction or the config', 'NO_PRIVATE_KEY', null); | ||
} | ||
const signedTransaction = JSON.stringify((0, crypto_1.createJWS)(JSON.stringify(this.transaction), key)); | ||
const signedTransaction = (0, crypto_1.createJWS)(JSON.stringify(this.transaction), key); | ||
this.signedTransaction = signedTransaction; | ||
@@ -94,0 +110,0 @@ return this; |
@@ -1,2 +0,1 @@ | ||
import { ContextStatement } from './ContextTypes'; | ||
type InsertObject = { | ||
@@ -6,3 +5,3 @@ [key: string]: string | string[] | number | number[] | boolean | boolean[] | InsertStatement; | ||
export type InsertArray = Array<InsertObject>; | ||
type DeleteObject = { | ||
export type DeleteObject = { | ||
[key: string]: string | DeleteStatement; | ||
@@ -13,6 +12,3 @@ }; | ||
export type DeleteStatement = DeleteObject | DeleteArray; | ||
export type UpsertStatement = { | ||
'@context'?: ContextStatement; | ||
ledger?: string; | ||
} & InsertStatement; | ||
export type UpsertStatement = InsertStatement; | ||
export {}; |
import { IFlureeConfig } from '../interfaces/IFlureeConfig'; | ||
export declare const generateFetchParams: (config: IFlureeConfig, endpoint: string) => [string, { | ||
export declare const generateFetchParams: (config: IFlureeConfig, endpoint: string, contentType?: string) => [string, { | ||
method: string; | ||
@@ -4,0 +4,0 @@ headers: { |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.generateFetchParams = void 0; | ||
const generateFetchParams = (config, endpoint) => { | ||
const generateFetchParams = (config, endpoint, contentType = "application/json") => { | ||
const { host, port, isFlureeHosted, apiKey } = config; | ||
@@ -19,3 +19,3 @@ let url; | ||
const headers = { | ||
'Content-Type': 'application/json', | ||
'Content-Type': contentType, | ||
}; | ||
@@ -22,0 +22,0 @@ if (apiKey) { |
import { IFlureeTransaction } from '../interfaces/IFlureeTransaction'; | ||
import { InsertStatement } from '../types/TransactionTypes'; | ||
import { DeleteStatement, InsertStatement } from '../types/TransactionTypes'; | ||
import { WhereArray } from '../types/WhereTypes'; | ||
type Entity = { | ||
[key: string]: string | string[] | number | number[] | boolean | boolean[] | Entity | Entity[] | (string | number | boolean | Entity)[]; | ||
[key: string]: string | string[] | number | number[] | Entity | Entity[] | (string | number | Entity)[]; | ||
}; | ||
@@ -10,5 +10,7 @@ type EntityMap = { | ||
}; | ||
export declare function flattenTxn(input: Entity | Entity[], idAlias: string): EntityMap; | ||
export declare function convertTxnToWhereDelete(flattenedTxn: EntityMap, idAlias: string): WhereArray; | ||
export declare function flattenTxn(txn: InsertStatement, idAlias: string): EntityMap; | ||
export declare function convertTxnToWhereDelete(flattenedTxn: EntityMap, idAlias: string): [WhereArray, DeleteStatement]; | ||
export declare function generateWhereDeleteForIds(ids: string[], idAlias: string): WhereArray; | ||
export declare const handleUpsert: (upsertTxn: InsertStatement, idAlias: string) => IFlureeTransaction; | ||
export declare const handleDelete: (id: string | string[], idAlias: string) => IFlureeTransaction; | ||
export {}; |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.handleUpsert = exports.convertTxnToWhereDelete = exports.flattenTxn = void 0; | ||
exports.handleDelete = exports.handleUpsert = exports.generateWhereDeleteForIds = exports.convertTxnToWhereDelete = exports.flattenTxn = void 0; | ||
function processEntity(entity, map, idAlias) { | ||
@@ -37,3 +37,7 @@ const entityId = entity[idAlias]; | ||
} | ||
function flattenTxn(input, idAlias) { | ||
function flattenTxn(txn, idAlias) { | ||
return flattenEntity(txn, idAlias); | ||
} | ||
exports.flattenTxn = flattenTxn; | ||
function flattenEntity(input, idAlias) { | ||
const map = {}; | ||
@@ -49,5 +53,5 @@ const txns = Array.isArray(input) ? input : [input]; | ||
} | ||
exports.flattenTxn = flattenTxn; | ||
function convertTxnToWhereDelete(flattenedTxn, idAlias) { | ||
const where = []; | ||
const whereClause = []; | ||
const deleteClause = []; | ||
let i = 1; | ||
@@ -59,18 +63,40 @@ for (const key in flattenedTxn) { | ||
entityKeys.forEach((k) => { | ||
where.push(Object.assign(Object.assign({}, whereEntity), { [k]: `?${i}` })); | ||
const expression = Object.assign(Object.assign({}, whereEntity), { [k]: `?${i}` }); | ||
whereClause.push(['optional', expression]); | ||
deleteClause.push(expression); | ||
i++; | ||
}); | ||
} | ||
return [whereClause, deleteClause]; | ||
} | ||
exports.convertTxnToWhereDelete = convertTxnToWhereDelete; | ||
function generateWhereDeleteForIds(ids, idAlias) { | ||
const where = []; | ||
for (const index in ids) { | ||
where.push({ | ||
[idAlias]: ids[index], | ||
[`?p${index}`]: `?o${index}`, | ||
}); | ||
} | ||
return where; | ||
} | ||
exports.convertTxnToWhereDelete = convertTxnToWhereDelete; | ||
exports.generateWhereDeleteForIds = generateWhereDeleteForIds; | ||
const handleUpsert = (upsertTxn, idAlias) => { | ||
const flattenedTxn = flattenTxn(upsertTxn, idAlias); | ||
const whereDelete = convertTxnToWhereDelete(flattenedTxn, idAlias); | ||
const [whereClause, deleteClause] = convertTxnToWhereDelete(flattenedTxn, idAlias); | ||
return { | ||
where: whereClause, | ||
delete: deleteClause, | ||
insert: upsertTxn, | ||
}; | ||
}; | ||
exports.handleUpsert = handleUpsert; | ||
const handleDelete = (id, idAlias) => { | ||
const idList = !Array.isArray(id) ? [id] : id; | ||
const whereDelete = generateWhereDeleteForIds(idList, idAlias); | ||
return { | ||
where: whereDelete, | ||
delete: whereDelete, | ||
insert: upsertTxn, | ||
}; | ||
}; | ||
exports.handleUpsert = handleUpsert; | ||
exports.handleDelete = handleDelete; |
{ | ||
"name": "@fluree/fluree-client", | ||
"version": "1.0.6", | ||
"version": "1.0.7", | ||
"description": "", | ||
@@ -40,3 +40,3 @@ "main": "dist/index.js", | ||
"dependencies": { | ||
"@fluree/crypto": "^3.0.0-alpha1", | ||
"@fluree/crypto": "^3.0.0", | ||
"@types/uuid": "^9.0.8", | ||
@@ -43,0 +43,0 @@ "dotenv": "^16.4.1", |
@@ -88,2 +88,3 @@ # Fluree Client SDK for TypeScript/JavaScript | ||
- [transact()](#transact) | ||
- [delete()](#delete) | ||
- [upsert()](#upsert) | ||
@@ -170,2 +171,35 @@ - [history()](#history) | ||
#### `delete()` | ||
The `delete()` method creates a new `TransactionInstance` for deleting subjects by `@id` in the Fluree database. The `TransactionInstance` can then be used to sign and send delete transactions to the Fluree instance. | ||
> Delete is not an API endpoint in Fluree. This method helps to transform a single or list of subject identifiers (@id) into a _where/delete_ transaction that deletes the subject(s) and all facts about the subject(s). | ||
```js | ||
// Existing data: | ||
// [ | ||
// { "@id": "freddy", "name": "Freddy" }, | ||
// { "@id": "alice", "name": "Alice" } | ||
// ] | ||
const txnInstance = client.delete(['freddy']); | ||
const txnObject = txnInstance.getTransaction(); | ||
console.log(txnObject); | ||
// { | ||
// where: [{ '@id': 'freddy', ?p0: '?o0' }], | ||
// delete: [{ '@id': 'freddy', ?p0: '?o0' }], | ||
// ledger: ... | ||
// } | ||
const response = await txnInstance.send(); | ||
// New data state after txn: | ||
// [ | ||
// { "@id": "alice", "name": "Alice" } | ||
// ] | ||
``` | ||
#### `upsert()` | ||
@@ -188,3 +222,3 @@ | ||
const txnInstance = await client.upsert([ | ||
const txnInstance = client.upsert([ | ||
{ '@id': 'freddy', name: 'Freddy the Yeti' }, | ||
@@ -673,1 +707,20 @@ { '@id': 'alice', age: 25 }, | ||
``` | ||
``` | ||
``` | ||
## Running tests | ||
Before running tests, you'll need a `.env.local` file in the root of the project. | ||
This file needs to contain the following: | ||
``` | ||
TEST_NEXUS_LEDGER="fluree-jld/387028092978318" | ||
TEST_API_KEY="_DPu2OWxmJ-zRwnzNr8uL...5mfV1OsfOXcRmb35t02rp1gMxxSw" | ||
``` | ||
### Run tests | ||
In the root of the project, run: | ||
``` | ||
yarn test | ||
``` |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
99338
40
2067
722
Updated@fluree/crypto@^3.0.0