diff --git a/README.md b/README.md index 1a4c369..d86d88c 100644 --- a/README.md +++ b/README.md @@ -18,19 +18,17 @@ SDK for the Skyflow Data Privacy Vault. - [Require](#require) - [All imports](#all-imports) - [Vault APIs](#vault-apis) - - [Insert: vault.insert()](#insert-vaultinsert) + - [Insert: vault().insert()](#insert-vaultinsert) - [Example: Insert Records](#example-insert-records) - [Example: Upsert Records (update or insert)](#example-upsert-records-update-or-insert) - [Example: Insert with partial success support](#example-insert-with-partial-success-support) - [Detokenize: vault.detokenize()](#detokenize-vaultdetokenize) - [Detokenize example](#detokenize-example) - - [Get By IDs: vault.getById()](#get-by-ids-vaultgetbyid) - - [Example: Get Records by IDs](#example-get-records-by-ids) - [Get records by unique values: vault.get()](#get-records-by-unique-values-vaultget) - - [Example: Get records by ID(s)](#example-get-records-by-ids-1) - - [Example: Get records by unique field values](#example-get-records-by-unique-field-values) - - [Update records by IDs](#update-records-by-ids) - - [Example: Update records by IDs](#example-update-records-by-ids) + - [Example: Get records by ID(s)](#example-get-records-by-ids) + - [Example: Get records by unique column values](#example-get-records-by-unique-column-values) + - [Update records by ID](#update-records-by-id) + - [Example: Update records by ID](#example-update-records-by-id) - [Delete](#delete) - [Invoke Connection](#invoke-connection) - [Example: Invoke Connection](#example-invoke-connection) @@ -72,9 +70,10 @@ import { Skyflow } from 'skyflow-node'; ##### All imports ```javascript -import { Skyflow, // Vault client - generateBearerToken, isExpired, // JWT auth helpers - LogLevel, setLogLevel // logging options +import { + Skyflow, // Vault client + isExpired, // JWT auth helpers + LogLevel, // logging options } from 'skyflow-node' ``` @@ -88,118 +87,140 @@ To use this module, the Skyflow client must first be initialized as follows: import { Skyflow } from 'skyflow-node'; // Initialize the Skyflow Vault client -const vault = Skyflow.init({ - // Id of the vault that the client should connect to. - vaultID: 'string', - // URL of the vault that the client should connect to. - vaultURL: 'string', - // Helper function generates a Skyflow bearer token. - getBearerToken: auth, +const client : Skyflow = Skyflow({ + vaultConfigs: [ + { + // Id of the vault that the client should connect to. + vaultId: 'string', + // Id of the cluster that the client should connect to. + clusterId: 'string', + // environment to which the vault ID belongs + env: Env.PROD, + // vault level credentials + credentials: { + roles: ['string', 'string'], // optional, IDs for roles + context: 'string', // optional, Id of the context + credentialsString: 'string', // credentials JSON as a stringified version + }, + } + ], + connectionConfigs: [ + { + // Id of the connection that the client should connect to. + connectionId: 'string', + // URL of the connection that the client should connect to. + connectionUrl: 'string', + // connection level credentials + credentials: { + apiKey: 'string', // API key + }, + }, + ], + // environment to which the vault ID belongs + skyflowCredentials: { + path: 'string', // optional, path to credentials json file + }, + // optional, if not specified default is ERROR + logLevel: LogLevel.ERROR, }); - -// sample function to retrieve a bearer token from an environment variable -// customize this according to your environment and security posture -const auth = function () { - return new Promise((resolve, reject) => { - resolve(process.env.VAULT_BEARER_TOKEN); - }); -}, ``` -For the `getBearerToken` parameter, pass in a helper function that retrieves a Skyflow bearer token from your backend. This function will be invoked when the SDK needs to insert or retrieve data from the vault. +Pass the `SKYFLOW_CREDENTIALS` parameter as an environment variable. This variable will be used when the SDK needs to insert or retrieve data from the vault. All Vault APIs must be invoked using a vault client instance. -### Insert: vault.insert() +### Insert: vault().insert() -To insert data into your vault, use the `insert(data, options?)` method. +To insert data into your vault, use the `insert(request, options?)` method. ```js -vault.insert(data, options?); +vault('VAULT_ID').insert(request, options?); ``` -- **Records:** The first parameter records is a JSONObject that must have a records key and takes an array of records to be inserted into the vault as a value. -- **Options:** The second parameter options is an optional object that provides further options for your insert call, more details below. +- **Request:** The first parameter request is an object of insert request that must have a table name key and takes an array of rows to be inserted into the vault as a value. +- **Options:** The second parameter options is an optional class object that provides further options for your insert call, more details below. #### Example: Insert Records -An [example](https://github.com/skyflowapi/skyflow-node/blob/main/samples/vault-api/Insert.ts) of a simple insert call is given below: +An [example](https://github.com/skyflowapi/skyflow-node/blob/release/24.10.1/samples/vault-api/insert-records.ts) of a simple insert call is given below: ```javascript -const result = await vault.insert( - { - // records to be inserted - records: [ - { - fields: { - // fields by name - expiry_date: '12/2026', - card_number: '411111111111111', - }, - // table name - table: 'cards', - }, - ], - }, - // options - { - // return tokens instead of real values - tokens: true, - } +// rows to be inserted +const insertData: Array = [ + { card_number: '4111111111111111', card_cvv: '1234' }, +]; + +// table name +const tableName: string = 'TABLE_NAME'; + +//creating insert request +const insertReq: InsertRequest = new InsertRequest( + tableName, + insertData, ); +const insertOptions: InsertOptions = new InsertOptions(); +//use setters for setting options +// return tokens instead of real values +insertOptions.setReturnTokens(true); + +skyflowClient.vault('VAULT_ID').insert( + insertReq, + insertOptions +).then((resp: InsertResponse) => { + console.log(resp); +}).catch((err: SkyflowError) => { + console.log(JSON.stringify(err)); +}); ``` **Sample response:** ```json { - "records": [ + "insertedFields": [ { - "table": "cards", - "fields": { - "card_number": "f37186-e7e2-466f-91e5-48e2bcbc1", - "expiry_date": "1989cb56-63a-4482-adf-1f74cd1a5", - }, + "card_number": "f37186-e7e2-466f-91e5-48e2bcbc1", + "card_cvv": "1989cb56-63a-4482-adf-1f74cd1a5", }, ], + "errors": [], } ``` #### Example: Upsert Records (update or insert) -Insert call [example](https://github.com/skyflowapi/skyflow-node/blob/main/samples/vault-api/UpsertSupport.ts) with upsert support: +Insert call [example](https://github.com/skyflowapi/skyflow-node/blob/release/24.10.1/samples/vault-api/upsert.ts) with upsert support: ```javascript -const response = vault.insert({ - // records to be inserted - records: [{ - fields: { - expiry_date: '12/2026', - card_number: '411111111111111', - }, - table: 'cards', - }], -}, { - // optional options - tokens: true, - // To conditionally insert OR update based on a field - upsert: [ - { - table: 'cards', // Name of the table in the vault. - column: 'card_number', // Name of the column in the vault. Must be defined as `unique`. - } - ] -}); +// rows to be inserted +const insertData: Array = [ + { card_number: '4111111111111111', card_cvv: '1234' }, +]; -response.then( - (res) => { - console.log(JSON.stringify(res)); - }, - (err) => { - console.log(JSON.stringify(err)); - } -).catch((err) => { +// table name +const tableName: string = 'TABLE_NAME'; + +//creating insert request +const insertReq: InsertRequest = new InsertRequest( + tableName, + insertData, +); + +const insertOptions: InsertOptions = new InsertOptions(); +//use setters for setting options +// return tokens instead of real values +insertOptions.setReturnTokens(true); +// To conditionally insert OR update based on a field +// Name of the column in the vault. Must be defined as `unique`. +insertOptions.setUpsertColumn('card_number'); + +skyflowClient.vault('VAULT_ID').insert( + insertReq, + insertOptions +).then((resp: InsertResponse) => { + console.log(resp); +}).catch((err: SkyflowError) => { console.log(JSON.stringify(err)); }); ``` @@ -207,16 +228,14 @@ response.then( Samples Response: ```json { - "records": [ + "insertedFields": [ { - "table": "cards", - "fields": { - "skyflow_id": "16419435-aa63-4823-aae7-19c6a2d6a19f", - "card_number": "f3907186-e7e2-466f-91e5-48e12c2bcbc1", - "cvv": "1989cb56-63da-4482-a2df-1f74cd0dd1a5", - }, - } - ] + "skyflowId": "16419435-aa63-4823-aae7-19c6a2d6a19f", + "card_number": "f3907186-e7e2-466f-91e5-48e12c2bcbc1", + "card_cvv": "1989cb56-63da-4482-a2df-1f74cd0dd1a5", + }, + ], + "errors" : [], } ``` @@ -224,45 +243,38 @@ Samples Response: Insert with partial success support -Insert call [example](https://github.com/skyflowapi/skyflow-node/blob/main/samples/vault-api/InsertWithContinueOnError.ts) with contiueOnError support: +Insert call [example](https://github.com/skyflowapi/skyflow-node/blob/release/24.10.1/samples/vault-api/insert-continue-on-error.ts) with contiueOnError support: ```javascript -const response = vault.insert({ - records: [ - { - fields: { - expiry_date: '12/2026', - card_number: '411111111111111', - namee: 'john doe', - }, - table: 'cards', - }, - { - fields: { - expiry_date: '12/2027', - card_number: '411111111111111', - name: 'jane doe', - }, - table: 'cards', - } - ], -}, -{ - // return tokens instead of real values - tokens: true, - // Ignore failures and keep going. Response will include errors with index value. - continueOnError: true, -}); +// rows to be inserted +const insertData: Array = [ + { card_number: '4111111111111111', card_cvv: '1234' }, + { card_umber: '4111111111111111', card_cvv: '1234' }, +]; -response.then( - (res) => { - console.log(JSON.stringify(res)); - }, - (err) => { +// table name +const tableName: string = 'TABLE_NAME'; + +//creating insert request +const insertReq: InsertRequest = new InsertRequest( + tableName, + insertData, +); + +const insertOptions: InsertOptions = new InsertOptions(); +//use setters for setting options +// return tokens instead of real values +insertOptions.setReturnTokens(true); +// if continue on error is set true we will return requestIndex for errors +insertOptions.setContinueOnError(true); + +skyflowClient.vault('VAULT_ID').insert( + insertReq, + insertOptions +).then((resp: InsertResponse) => { + console.log(resp); +}).catch((err: SkyflowError) => { console.log(JSON.stringify(err)); - } -).catch((err) => { - console.log(JSON.stringify(err)); }); ``` @@ -270,66 +282,84 @@ response.then( ```json { - "records": [ + "insertedFields": [ { - "table": "cards", - "fields": { - "skyflow_id": "16419435-aa63-4823-aae7-19c6a2d6a19f", - "card_number": "f3907186-e7e2-466f-91e5-48e12c2bcbc1", - "expiry_date": "1989cb56-63da-4482-a2df-1f74cd0dd1a5", - "name": "245d3a0f-a2d3-443b-8a20-8c17de86e186", - }, - "request_index": 1, + "skyflowId": "16419435-aa63-4823-aae7-19c6a2d6a19f", + "card_number": "f3907186-e7e2-466f-91e5-48e12c2bcbc1", + "card_cvv": "1989cb56-63da-4482-a2df-1f74cd0dd1a5", + "request_index": 0, } ], "errors": [ { - "error": { - "code":400, - "description":"Invalid field present in JSON namee - requestId: 87fb2e32-6287-4e61-8304-9268df12bfe8", - "request_index": 0, - } + "code":400, + "description":"Invalid field present in JSON card_umber.", + "request_index": 1, } ] } ``` -### Detokenize: vault.detokenize() +### Detokenize: vault().detokenize() Returns values for provided tokens. -In order to retrieve data from your vault using tokens that you have previously generated for that data, you can use the `detokenize(data)` method. The first parameter must have a records key that takes an array of tokens to be fetched from the vault, as shown below. +In order to retrieve data from your vault using tokens that you have previously generated for that data, you can use the `detokenize(request)` method. The first parameter must have a request key that takes an array of tokens to be fetched from the vault and the redaction type, as shown below. ```javascript -data = { - records: [{ - token: 'string', // Required, token for the record to be fetched. - redaction: Skyflow.RedactionType // Optional, redaction type to be applied ex: Skyflow.RedactionType.PLAIN_TEXT - }] -} -``` +// Required, tokens for the records to be fetched. +const detokenizeData: Array = [ + 'string', + 'string', + 'string', +]; + +// Optional, redaction type to be applied ex: Skyflow.RedactionType.PLAIN_TEXT +const redactionType: RedactionType = RedactionType.REDACTED; -`Skyflow.RedactionType` accepts one of four values: +const detokenizeRequest: DetokenizeRequest = new DetokenizeRequest( + detokenizeData, + redactionType, +); +``` +`RedactionType` accepts one of four values: * `PLAIN_TEXT` * `MASKED` * `REDACTED` * `DEFAULT` Note: -- `redaction` defaults to Skyflow.RedactionType.PLAIN_TEXT. +- `redaction` defaults to RedactionType.PLAIN_TEXT. #### Detokenize example -An [example](https://github.com/skyflowapi/skyflow-node/blob/main/samples/vault-api/Detokenize.ts) of a detokenize call: +An [example](https://github.com/skyflowapi/skyflow-node/blob/release/24.10.1/samples/vault-api/detokenize-records.ts) of a detokenize call: ```javascript -const result = await vault.detokenize({ - records: [ - { - token: '4017-f72b-4f5c-9b-8e719', - redaction: Skyflow.RedactionType.PLAIN_TEXT - }, - ], +const detokenizeData: Array = [ + '4017-f72b-4f5c-9b-8e719', +]; + +const redactionType: RedactionType = RedactionType.PLAIN_TEXT; + +const detokenizeRequest: DetokenizeRequest = new DetokenizeRequest( + detokenizeData, + redactionType, +); + +const detokenizeOptions: DetokenizeOptions = new DetokenizeOptions(); +// options can be set using setters +detokenizeOptions.setContinueOnError(true); + +detokenizeOptions.setDownloadURL(false); + +skyflowClient.vault('VAULT_ID').detokenize( + detokenizeRequest, + detokenizeOptions +).then((response: DetokenizeResponse) => { + console.log(response); +}).catch((error: SkyflowError) => { + console.log(JSON.stringify(error)); }); ``` @@ -337,401 +367,321 @@ Sample response: ```json { - "records": [ + "detokenizedFields": [ { "token": "110dc-6f76-19-bd3-9051051", "value": "1990-01-01", }, ], + "errors": [], } ``` -### Get By IDs: vault.getById() +### Tokenize: vault().tokenize() -In order to retrieve data from your vault using SkyflowIDs, use the `getById(records)` method. The records parameter takes a JSON Object that should contain an array of SkyflowIDs to be fetched, as shown below: +In order to tokenize data, you can use the `tokenize(request)` method. The first parameter is a request object that takes an array of `TokenizeRequestType`, as shown below. -```javascript -data = { - records: [{ - // List of skyflow_ids for the records to be fetched - ids: ['id1', 'id2'], - // Name of table holding the above skyflow_ids - table: 'NAME_OF_SKYFLOW_TABLE', - // Redaction to be applied to retrieved data - redaction: Skyflow.RedactionType.PLAIN_TEXT, - }] -}; -``` +```js +import { TokenizeRequest, TokenizeRequestType } from 'skyflow-node'; -`Skyflow.RedactionType` accepts one of four values: -* `PLAIN_TEXT` -* `MASKED` -* `REDACTED` -* `DEFAULT` +// tokenize only supports value and columngroup +// sample data +const tokenizeValues: Array = [ + { value: 'VALUE', columnGroup: 'COLUMN_GROUP' }, + { value: 'VALUE', columnGroup: 'COLUMN_GROUP' }, +]; -You must apply a redaction type to retrieve data. +const tokenReq: TokenizeRequest = new TokenizeRequest( + tokenizeValues, +); +``` -#### Example: Get Records by IDs +Sample usage -An [example](https://github.com/skyflowapi/skyflow-node/blob/main/samples/vault-api/GetById.ts) of `getById` call: +An [example](https://github.com/skyflowapi/skyflow-node/blob/release/24.10.1/samples/vault_api/tokenize-records.ts) of a tokenize call: ```javascript -let skyflowIds = [ - 'f8622-b557-4c6b-a12c-c0b0bfd9', - 'da26de53-95d5-4db-99db-8d35ff9' +// tokenize only supports value and columngroup +// sample data +const tokenizeValues: Array = [ + { value: '4111111111111111', columnGroup: 'card_number_cg' }, + { value: '42424242424242424', columnGroup: 'card_number_cg' } ]; -let record = { - ids: skyflowIds, - table: 'cards', - redaction: RedactionType.PLAIN_TEXT -}; - -let invalidIds = ['invalid Skyflow ID']; -let badRecord = { - ids: invalidIds, - table: 'cards', - 'redaction': RedactionType.PLAIN_TEXT -}; - -let records = { - records: [record, badRecord] -}; +const tokenReq: TokenizeRequest = new TokenizeRequest( + tokenizeValues, +); -const result = client.getById(records); -result.then( - (res) => { - console.log(JSON.stringify(res)); - }).catch((err) => { +skyflowClient.vault('VAULT_ID').tokenize( + tokenReq, +).then((resp: TokenizeResponse) => { + console.log(resp); +}).catch((err: SkyflowError) => { console.log(JSON.stringify(err)); }); ``` Sample response: -```json +```javascript { - "records": [ - { - "fields": { - "card_number": "4111111111111111", - "expiry_date": "11/35", - "fullname": "myname", - "skyflow_id": "f8d2-b557-4c6b-a12c-c5ebfd9" - }, - "table": "cards" - }, - { - "fields": { - "card_number": "4111111111111111", - "expiry_date": "10/23", - "fullname": "sam", - "skyflow_id": "da53-95d5-4bdb-99db-8d8c5ff9" - }, - "table": "cards" - } + tokens: [ + '5479-4229-4622-1393', + '8989-7867-7887-0987', ], - "errors": [ - { - "error": { - "code": "404", - "description": "No Records Found" - }, - "skyflow_ids": [ - "invalid Skyflow ID" - ] - } - ] + errors: [], } ``` -### Get records by unique values: vault.get() -To retrieve data from your vault using SkyflowIDs or unique column values, use the `get(records)` method. The `records` parameter takes a JSONObject that should contain either an array of SkyflowIDs or a unique column name and values to fetch the records, as shown below: +### Get records by unique values: vault().get() -```javascript -data = { - records: [ - { - // List of skyflow_ids for the records to fetch. - ids: ['SKYFLOW_ID_1', 'SKYFLOW_ID_2'], // Optional - // Name of table holding the records in the vault. - table: 'NAME_OF_SKYFLOW_TABLE', - // Redaction type to apply to retrieved data. - redaction: Skyflow.RedactionType, - // Unique column name in the vault. - columnName: 'UNIQUE_COLUMN_NAME', // Optional - // List of given unique column values. - columnValues: ['', '', ''], // Required if column name is provided - }, - ], -}; -``` - -Note: You cannot pass an array of skyflow_ids and unique column details together. Using column name and column value with `skyflow_ids` will return an error message. +To retrieve data from your vault using SkyflowIDs or unique column values, use the `get(request)` method. The `request` parameter takes a column value or get request object that should contain either an array of a unique column name and column values or skyflowIds to fetch the records, as shown below: #### Example: Get records by ID(s) - -[Example](https://github.com/skyflowapi/skyflow-node/blob/main/samples/vault-api/Get.ts) to get records using skyflowIds: +[Example](https://github.com/skyflowapi/skyflow-node/blob/release/24.10.1/samples/vault-api/get-records.ts) to get records using skyflowIds: ```javascript -let skyflowIds = [ - 'f8622-b557-4c6b-a12c-c0b0bfd9', - 'da26de53-95d5-4db-99db-8d35ff9', +const getIds: Array = [ + 'SKYFLOW_ID1', + 'SKYFLOW_ID2', ]; -let record = { - ids: skyflowIds, - table: 'cards', - redaction: RedactionType.PLAIN_TEXT, -}; - -let records = { - records: [record], -}; +const tableName: string = 'TABLE_NAME'; -const result = vault.get(records); -result - .then((res) => { - console.log(JSON.stringify(res)); - }) - .catch((err) => { - console.log(JSON.stringify(err)); - }); -``` +const getRequest: GetRequest = new GetRequest( + tableName, + getIds, +); -Response: +const getOptions: GetOptions = new GetOptions(); +//use setters of setting options refer to skyflow docs for more options +getOptions.setReturnTokens(true); -```json -{ - "records":[ - { - "fields":{ - "card_number":"4111111111111111", - "expiry_date":"11/35", - "fullname":"myname", - "id":"f8d2-b557-4c6b-a12c-c5ebfd9" - }, - "table":"cards" - }, - { - "fields":{ - "card_number":"4111111111111111", - "expiry_date":"10/23", - "fullname":"sam", - "id":"da53-95d5-4bdb-99db-8d8c5ff9" - }, - "table":"cards" - } - ] -} +skyflowClient.vault('VAULT_ID').get( + getRequest, + getOptions +).then((response: GetResponse) => { + console.log(response); +}).catch((error: SkyflowError) => { + console.log(JSON.stringify(error)); +}); ``` -#### Example: Get records by unique field values +Note: You cannot pass an array of skyflow_ids and unique column details together. Using column name and column value with `skyflow_ids` will return an error message. -[Example](https://github.com/skyflowapi/skyflow-node/blob/main/samples/vault-api/Get.ts) to get records using unique column names and values: +#### Example: Get records by unique column values +[Example](https://github.com/skyflowapi/skyflow-node/blob/release/24.10.1/samples/vault-api/get-column-values.ts) to get records using unique column values: ```javascript -let record = { - table: 'cards', - redaction: RedactionType.PLAIN_TEXT, - columnName: 'card_id', - columnValues: ['123', '456'], -}; +const columnValues: Array = [ + 'VALUE1', + 'VALUE2', +]; -let records = { - records: [record], -}; +const tableName: string = 'TABLE_NAME'; +//Name of the column. It must be configured as unique in the schema. +const columnName: string = 'COLUMN_NAME'; -const result = vault.get(records); -result - .then((res) => { - console.log(JSON.stringify(res)); - }) - .catch((err) => { - console.log(JSON.stringify(err)); - }); +const getRequest: GetColumnRequest = new GetColumnRequest( + tableName, + columnName, + columnValues, //Column values of the records to return +); + +const getOptions: GetOptions = new GetOptions(); +//use setters of setting options refer to skyflow docs for more options +getOptions.setReturnTokens(true); + +skyflowClient.vault('VAULT_ID').get( + getRequest, + getOptions, +).then((response: GetResponse) => { + console.log(response); +}).catch((error: SkyflowError) => { + console.log(JSON.stringify(error)); +}); ``` Response: + ```json { - "records":[ + "data":[ { - "fields":{ - "card_id":"123", - "expiry_date":"11/35", - "fullname":"myname", - "id":"f8d2-b557-4c6b-a12c-c5ebfd9" - }, - "table":"cards" + "card_number":"4111111111111111", + "expiry_date":"11/35", + "fullname":"myname", + "id":"f8d2-b557-4c6b-a12c-c5ebfd9" }, { - "fields":{ - "card_id":"456", - "expiry_date":"10/23", - "fullname":"sam", - "id":"da53-95d5-4bdb-99db-8d8c5ff9" - }, - "table":"cards" + "card_number":"4111111111111111", + "expiry_date":"10/23", + "fullname":"sam", + "id":"da53-95d5-4bdb-99db-8d8c5ff9" } - ] + ], + "errors": [], } ``` -### Update records by IDs +### Update records by ID -To update records in your vault by skyflow_id, use the `update(records, options)` method. The first parameter, `records`, is a JSONObject that must have a records key and takes an array of records to update as a value in the vault. The options parameter takes an object of optional parameters for the update and includes an option to return tokenized data for the updated fields. +To update records in your vault by skyflow_id, use the `update(request, options)` method. The first parameter, `request`, is a update request that must have the table name and takes an object which contains `skyflowId` key to update as a value in the vault. The options parameter takes an object of optional parameters for the update and includes an update options object to return tokenized data for the updated fields. Call schema: ```js -const updateInput = { - records: [ // Array of records to update. - { - id: '', // Skyflow_id of record to update. - table: '', // Table name of given Skyflow_id. - fields: { // Fields to update. - '': '', - '': '', - }, - }, - ] -}; +// sample data +const updateData: Object = { skyflowId:'SKYFLOW_ID', field: 'VALUE' }; -const options = { // Optional - // Option to return updated field tokens in response. - // Defaults to 'true'. - tokens: true, -} +const tableName: string = 'TABLE_NAME'; + +const updateReq: UpdateRequest = new UpdateRequest( + tableName, + updateData, +); + +const updateOptions: UpdateOptions = new UpdateOptions(); + +updateOptions.setReturnTokens(true); + +skyflowClient.vault('VAULT_ID').update( + updateReq, + updateOptions, +).then((resp: UpdateResponse) => { + console.log(resp); + console.log(updateData) +}).catch((err: SkyflowError) => { + console.log(JSON.stringify(err)); +}); ``` -#### Example: Update records by IDs +#### Example: Update records by ID -[Example](https://github.com/skyflowapi/skyflow-node/blob/main/samples/vault-api/Update.ts) to update by ID using `skyflow_ids`: +[Example](https://github.com/skyflowapi/skyflow-node/blob/release/24.10.1/samples/vault-api/Update.ts) to update by ID using `skyflowId`: ```js -const updateInput = { - records: [ - { - id: '29ebda8d-5272-4063-af58-15cc674e332b', // Valid record id. - table: 'cards', - fields: { - card_number: '5105105105105100', - cardholder_name: 'Thomas', - expiration_date: '07/2032', - ssn: '123-45-6722', - }, - }, - ], -}; +// sample data +const updateData: Object = { skyflowId:'29fac46e-5e58-4403-b0da-123436cf4c3d',card_number: '12333333333333444444' }; -const options = { tokens: true }; +const tableName: string = 'table1'; -const response = vault.update(updateInput, options); -console.log(response); +const updateReq: UpdateRequest = new UpdateRequest( + tableName, + updateData, +); + +const updateOptions: UpdateOptions = new UpdateOptions(); + +updateOptions.setReturnTokens(true); + +skyflowClient.vault('VAULT_ID').update( + updateReq, + updateOptions, +).then((resp: UpdateResponse) => { + console.log(resp); + console.log(updateData) +}).catch((err: SkyflowError) => { + console.log(JSON.stringify(err)); +}); ``` Response: ```json { - "records":[ - { - "id": "29ebda8d-5272-4063-af58-15cc674e332b", - "fields":{ - "card_number": "93f28226-51b0-4f24-8151-78b5a61f028b", - "cardholder_name": "0838fd08-9b51-4db2-893c-48542f3b121e", - "expiration_date": "91d7ee77-262f-4d5d-8286-062b694c81fd", - "ssn": "e28bf55d-f3d8-49a6-aad9-71a13db54b82", - }, - "table": "cards", - } - ] + "skyflowId": "29ebda8d-5272-4063-af58-15cc674e332b", + "card_number": "93f28226-51b0-4f24-8151-78b5a61f028b", } ``` ### Delete -To delete data from the vault, use the `delete(records, options?)` method of the Skyflow client. The `records` parameter takes an array of records with `id` and `table` to delete in the following format. The `options` parameter is optional and takes an object of deletion parameters. Currently, there are no supported deletion parameters. +To delete data from the vault, use the `delete(request)` method of the Skyflow client. The `request` parameter takes an delete request object with list of `skyflowIds` and `table` to delete in the following format. Call schema: ```js -const deleteInput = { - records: [ - { - id: "", // skyflow id of the record to delete - table: "" // Table from which the record is to be deleted - }, - { - // ...additional records here - }, - ] -}; +const deleteIds: Array = [ + 'SKYFLOW_ID1', // skyflow id of the record to delete + 'SKYFLOW_ID2', + 'SKYFLOW_ID3', +]; -const options = { - // Optional -} +const tableName: string = 'TABLE_NAME'; // Table from which the record is to be deleted + +const deleteRequest: DeleteRequest = new DeleteRequest( + tableName, + deleteIds, +); ``` -[Example](https://github.com/skyflowapi/skyflow-node/blob/main/samples/vault-api/Delete.ts) to delete by ID using `skyflow_ids` +[Example](https://github.com/skyflowapi/skyflow-node/blob/release/24.10.1/samples/vault-api/Delete.ts) to delete by ID using `skyflowIds` ```js -const deleteInput = { - records: [ - { - id: "29ebda8d-5272-4063-af58-15cc674e332b", - table: "cards", - }, - { - id: "d5f4b926-7b1a-41df-8fac-7950d2cbd923", - table: "cards", - } - ], -}; +const deleteIds: Array = [ + "29ebda8d-5272-4063-af58-15cc674e332b", + "d5f4b926-7b1a-41df-8fac-7950d2cbd923" +]; -const options = {}; +const tableName: string = 'table1'; // TABLE_NAME -const response = skyflowClient.delete(deleteInput, options); -console.log(response); +const deleteRequest: DeleteRequest = new DeleteRequest( + tableName, + deleteIds, +); + +// will return first Vault ID +skyflowClient.vault().delete( + deleteRequest, +).then((resp: DeleteResponse) => { + console.log(resp); +}).catch((err: SkyflowError) => { + console.log(JSON.stringify(err)); +}); ``` Response: ```json { - "records": [ - { - "skyflow_id": "29ebda8d-5272-4063-af58-15cc674e332b", - "deleted": true, - }, - { - "skyflow_id": "29ebda8d-5272-4063-af58-15cc674e332b", - "deleted": true, - } - ] + "deletedIds": [ + "29ebda8d-5272-4063-af58-15cc674e332b", + "d5f4b926-7b1a-41df-8fac-7950d2cbd923", + ], + "errors": [], } ``` ### Invoke Connection -Using Connection, you can integrate your server-side application with third party APIs and services without directly handling sensitive data. Prior to using a connection, you have to create a connection and have a connectionURL already generated. Once you have the connectionURL, you can invoke a connection by using the `invokeConnection(config)` method. The config object must include a connectionURL and methodName. The other fields are optional. +Using Connection, you can integrate your server-side application with third party APIs and services without directly handling sensitive data. Prior to using a connection, you have to create a connection and have a connectionURL already generated. Once you have the connectionURL, you can invoke a connection by using the `invoke(request)` method. The config object must include a methodName. The other fields are optional. ```javascript -data = { - connectionURL: '', - methodName: Skyflow.RequestMethod.POST, - requestHeader: { - Authorization: '', - }, - pathParams: { - card_number: '', - }, - requestBody: { - expirationDate: { - mm: '01', - yy: '46', - }, - }, +const body: Object = { + 'KEY1': 'VALUE1', + 'KEY2': 'VALUE2', }; + +const pathParams: Object = { + 'KEY1': 'VALUE1', + 'KEY2': 'VALUE2', +}; + +const queryParams: Object = { + 'KEY1': 'VALUE1', + 'KEY2': 'VALUE2', +}; + +const header: Object = { + 'Content-Type': 'application/json', +}; + +const method: Method = RequestMethod.POST; + +const invokeReq: InvokeConnectionRequest = new InvokeConnectionRequest( + method, + body, + headers, +); ``` Supported content-types for the response: @@ -740,45 +690,34 @@ Supported content-types for the response: Supported method names: -* GET: `Skyflow.RequestMethod.GET` -* POST: `Skyflow.RequestMethod.POST` -* PUT: `Skyflow.RequestMethod.PUT` -* PATCH: `Skyflow.RequestMethod.PATCH` -* DELETE: `Skyflow.RequestMethod.DELETE` +* GET: `RequestMethod.GET` +* POST: `RequestMethod.POST` +* PUT: `RequestMethod.PUT` +* PATCH: `RequestMethod.PATCH` +* DELETE: `RequestMethod.DELETE` -**pathParams, queryParams, requestHeader, requestBody** are the JSON objects that will be sent through the gateway integration URL. +**pathParams, queryParams, headers, body** are the JSON objects that will be sent through the gateway integration URL. #### Example: Invoke Connection -An [example](https://github.com/skyflowapi/skyflow-node/blob/main/samples/vault-api/InvokeConnection.ts) of `invokeConnection`: +An [example](https://github.com/skyflowapi/skyflow-node/blob/release/24.10.1/samples/vault-api/InvokeConnection.ts) of `invokeConnection`: ```javascript -const result = client.invokeConnection({ - connectionURL: '', - methodName: Skyflow.RequestMethod.POST, - requestHeader: { - 'Content-Type': 'application/json', - Authorization: '', - }, - pathParams: { - card_number: '', - }, - requestBody: { - expirationDate: { - mm: '01', - yy: '46', - }, - }, -}); +const request = new InvokeRequest( + method, + body, + headers, + pathParams, + queryParams, +); -result - .then(response => { - console.log(JSON.stringify(response)); - }) - .catch(error => { - // Note: only text/plain and application/json errors are supported - console.log(JSON.stringify(error)); - }); +skyflowClient.connection().invoke( + request, +).then((resp: InvokeConnectionResponse) => { + console.log(resp); +}).catch((err: SkyflowError) => { + console.log(JSON.stringify(err)); +}); ``` Sample response: @@ -1190,15 +1129,37 @@ tokens(); ### Logging -The Skyflow Node.js SDK provides useful logging. By default the logging level of the SDK is set to `LogLevel.ERROR`. This can be changed by using `setLogLevel(logLevel)` as shown below: +The Skyflow Node.js SDK provides useful logging. By default the logging level of the SDK is set to `LogLevel.ERROR`. This can be changed by setting logLevel as shown below: ```javascript -import { setLogLevel, LogLevel } from 'skyflow-node'; +import { LogLevel } from 'skyflow-node'; ``` ```javascript -// Sets the Skyflow SDK log level to INFO -setLogLevel(LogLevel.INFO); +const client : Skyflow = Skyflow({ + vaultConfigs: [ + { + // Id of the vault that the client should connect to. + vaultId: 'string', + // Id of the cluster that the client should connect to. + clusterId: 'string', + // environment to which the vault ID belongs + env: Env.PROD, + // vault level credentials + credentials: { + roles: ['string', 'string'], // optional, IDs for roles + context: 'string', // optional, Id of the context + credentialsString: 'string', // credentials JSON as a stringified version + }, + } + ], + // environment to which the vault ID belongs + skyflowCredentials: { + path: 'string', // optional, path to credentials json file + }, + // Sets the Skyflow SDK log level to INFO + logLevel: LogLevel.INFO, +}); ``` Current the following 5 log levels are supported: diff --git a/samples/vault-api/client-operations.ts b/samples/vault-api/client-operations.ts index e5fb90e..0d21808 100644 --- a/samples/vault-api/client-operations.ts +++ b/samples/vault-api/client-operations.ts @@ -1,8 +1,8 @@ -import { DeleteRequest, Env, LogLevel, Skyflow } from "skyflow-node"; +import { Credentials, DeleteRequest, Env, LogLevel, Skyflow, VaultConfig, SkyflowConfig } from 'skyflow-node'; try { // To generate Bearer Token from credentials string. - const cred = { + const cred: Object = { clientID: '', clientName: '', keyID: '', @@ -11,63 +11,71 @@ try { }; // please pass one of apiKey, token, credentialsString & path as credentials - const skyflowCredentials = { + const skyflowCredentials: Credentials = { credentialsString: JSON.stringify(cred), - } + }; // please pass one of apiKey, token, credentialsString & path as credentials - const credentials = { - token: "BEARER_TOKEN", // bearer token - } + const credentials: Credentials = { + token: 'BEARER_TOKEN', // bearer token + }; + + const primaryVaultConfig: VaultConfig = { + vaultId: 'VAULT_ID1', // primary vault + clusterId: 'CLUSTER_ID1', // ID from your vault URL Eg https://{clusterId}.vault.skyflowapis.com + env: Env.PROD, // Env by default it is set to PROD + credentials: credentials, // individual credentials + }; - const skyflowClient = new Skyflow({ + // skyflow config + const skyflowConfig: SkyflowConfig = { + // pass array vault configs vaultConfigs: [ - { - vaultId: "VAULT_ID1", // primary vault - clusterId: "CLUSTER_ID1", // ID from your vault URL Eg https://{clusterId}.vault.skyflowapis.com - env: Env.PROD, // Env by default it is set to PROD - credentials: credentials // individual credentials - } + primaryVaultConfig, ], skyflowCredentials: skyflowCredentials, // skyflow credentials will be used if no individual credentials are passed - logLevel: LogLevel.ERROR // set log level by default it is set to PROD - }); + logLevel: LogLevel.ERROR, // set log level by default it is set to PROD + }; + + // initialize skyflow client + const skyflowClient: Skyflow = new Skyflow(skyflowConfig); + + const vaultConfig: VaultConfig = { + vaultId: 'VAULT_ID2', // secondary vault + clusterId: 'CLUSTER_ID2', // ID from your vault URL Eg https://{clusterId}.vault.skyflowapis.com + env: Env.PROD, // Env by default it is set to PROD + // if you don't specify individual credentials, skyflow credentials will be used + }; //add vault config on the fly - skyflowClient.addVaultConfig( - { - vaultId: "VAULT_ID2", // secondary vault - clusterId: "CLUSTER_ID2", // ID from your vault URL Eg https://{clusterId}.vault.skyflowapis.com - env: Env.PROD, // Env by default it is set to PROD - // if you don't specify individual credentials, skyflow credentials will be used - } - ); + skyflowClient.addVaultConfig(vaultConfig); + const updatedVaultConfig: VaultConfig = { + vaultId: 'VAULT_ID2', // vault Id and cluster Id is unique + clusterId: 'CLUSTER_ID2', // ID from your vault URL Eg https://{clusterId}.vault.skyflowapis.com + credentials: credentials, //update credentials + }; //update vault config on the fly - skyflowClient.updateVaultConfig( - { - vaultId: "VAULT_ID2", // vault Id and cluster Id is unique - clusterId: "CLUSTER_ID2", // ID from your vault URL Eg https://{clusterId}.vault.skyflowapis.com - credentials: credentials, //update credentials - } - ); + skyflowClient.updateVaultConfig(updatedVaultConfig); //perform operations - const deleteIds = [ - "SKYLFOW_ID1", - "SKYLFOW_ID2" + const deleteIds: Array = [ + 'SKYLFOW_ID1', + 'SKYLFOW_ID2', ] - const deleteRequest = new DeleteRequest( - "TABLE_NAME", - deleteIds + const tableName: string = 'TABLE_NAME'; + + const deleteRequest: DeleteRequest = new DeleteRequest( + tableName, + deleteIds, ); //perform delete call if you don't specify vault() it will return the first valid vault - skyflowClient.vault("VAULT_ID2").delete(deleteRequest); + skyflowClient.vault('VAULT_ID2').delete(deleteRequest); //remove vault on the fly - skyflowClient.removeVaultConfig("VAULT_ID"); + skyflowClient.removeVaultConfig('VAULT_ID'); } catch (err) { console.log(JSON.stringify(err)); } \ No newline at end of file diff --git a/samples/vault-api/credentials-options.ts b/samples/vault-api/credentials-options.ts index dfa5aaa..d51f411 100644 --- a/samples/vault-api/credentials-options.ts +++ b/samples/vault-api/credentials-options.ts @@ -1,8 +1,9 @@ -import { DeleteRequest, Env, LogLevel, Skyflow } from "skyflow-node"; +import { Credentials, DeleteRequest, Env, LogLevel, Skyflow, VaultConfig, SkyflowConfig, DeleteResponse, SkyflowError } from 'skyflow-node'; + try { //NOTE : If you don't specify credentials at config level credentials or skyflow credentials, SDK will check SKYFLOW_CREDENTIALS key in your env // To generate Bearer Token from credentials string. - const cred = { + const cred: Object = { clientID: '', clientName: '', keyID: '', @@ -11,72 +12,82 @@ try { }; // please pass one of apiKey, token, credentialsString & path as credentials - const skyflowCredentials = { - credentialsString: JSON.stringify(cred) - } + const skyflowCredentials: Credentials = { + credentialsString: JSON.stringify(cred), + }; + + const credentials: Credentials = { + token: 'BEARER_TOKEN', // bearer token + // apiKey: 'API_KEY', //API_KEY + // path: 'PATH', //path to credentials file + // credentialsString: 'CREDENTIAL_STRING', // credentials as string + }; + + const primaryVaultConfig: VaultConfig = { + vaultId: 'VAULT_ID1', // primary vault + clusterId: 'CLUSTER_ID1', // ID from your vault URL Eg https://{clusterId}.vault.skyflowapis.com + env: Env.PROD, // Env by default it is set to PROD + }; - const credentials = { - token: "BEARER_TOKEN", // bearer token - // apiKey: "API_KEY", //API_KEY - // path: "PATH", //path to credentials file - // credentialsString: "CREDENTIAL_STRING", // credentials as string - } + const secondaryVaultConfig: VaultConfig = { + vaultId: 'VAULT_ID2', // secondary vault + clusterId: 'CLUSTER_ID2', // ID from your vault URL Eg https://{clusterId}.vault.skyflowapis.com + env: Env.PROD, // Env by default it is set to PROD + credentials: credentials, + }; - const skyflowClient = new Skyflow({ + const skyflowConfig: SkyflowConfig = { vaultConfigs: [ - { - vaultId: "VAULT_ID1", // primary vault - clusterId: "CLUSTER_ID1", // ID from your vault URL Eg https://{clusterId}.vault.skyflowapis.com - env: Env.PROD, // Env by default it is set to PROD - }, - { - vaultId: "VAULT_ID2", // primary vault - clusterId: "CLUSTER_ID2", // ID from your vault URL Eg https://{clusterId}.vault.skyflowapis.com - env: Env.PROD, // Env by default it is set to PROD - credentials: credentials, - } + primaryVaultConfig, + secondaryVaultConfig, ], skyflowCredentials: skyflowCredentials, // skyflow credentials will be used if no individual credentials are passed - logLevel: LogLevel.ERROR // set log level by default it is set to PROD - }); + logLevel: LogLevel.ERROR, // set log level by default it is set to PROD + }; - const primaryDeleteIds = [ + const skyflowClient: Skyflow = new Skyflow(skyflowConfig); + + const primaryDeleteIds: Array = [ 'SKYFLOW_ID1', 'SKYFLOW_ID2', 'SKYFLOW_ID3', - ] + ]; + + const primaryTableName: string = 'TABLE_NAME1'; // TABLE_NAME - const primaryDeleteRequest = new DeleteRequest( - "TABLE_NAME1", // TABLE_NAME - primaryDeleteIds + const primaryDeleteRequest: DeleteRequest = new DeleteRequest( + primaryTableName, + primaryDeleteIds, ); // VAULT_ID1 will use skyflowCredentials if you don't specify individual credentials at config level - skyflowClient.vault("VAULT_ID1").delete( - primaryDeleteRequest - ).then(resp => { + skyflowClient.vault('VAULT_ID1').delete( + primaryDeleteRequest, + ).then((resp: DeleteResponse) => { console.log(resp); - }).catch(err => { + }).catch((err: SkyflowError) => { console.log(JSON.stringify(err)); }); - const secondaryDeleteIds = [ + const secondaryDeleteIds: Array = [ 'SKYFLOW_ID4', 'SKYFLOW_ID5', 'SKYFLOW_ID6', - ] + ]; + + const secondaryTableName: string = 'TABLE_NAME2'; // TABLE_NAME - const secondaryDeleteRequest = new DeleteRequest( - "TABLE_NAME2", // TABLE_NAME - secondaryDeleteIds + const secondaryDeleteRequest: DeleteRequest = new DeleteRequest( + secondaryTableName, + secondaryDeleteIds, ); // VAULT_ID1 will use individual credentials at config level - skyflowClient.vault("VAULT_ID2").delete( + skyflowClient.vault('VAULT_ID2').delete( secondaryDeleteRequest - ).then(resp => { + ).then((resp: DeleteResponse) => { console.log(resp); - }).catch(err => { + }).catch((err: SkyflowError) => { console.log(JSON.stringify(err)); }); } catch (err) { diff --git a/samples/vault-api/data-residency.ts b/samples/vault-api/data-residency.ts index 900bea0..46fdfcf 100644 --- a/samples/vault-api/data-residency.ts +++ b/samples/vault-api/data-residency.ts @@ -1,8 +1,8 @@ -import { Env, GetRequest, GetResponse, InsertRequest, LogLevel, Skyflow } from "skyflow-node"; +import { Credentials, Env, GetRequest, GetResponse, InsertRequest, LogLevel, Skyflow, VaultConfig, SkyflowConfig, InsertResponse, SkyflowError } from 'skyflow-node'; try { // To generate Bearer Token from credentials string. - const cred = { + const cred: Object = { clientID: '', clientName: '', keyID: '', @@ -11,71 +11,79 @@ try { }; // please pass one of apiKey, token, credentialsString & path as credentials - const skyflowCredentials = { + const skyflowCredentials: Credentials = { credentialsString: JSON.stringify(cred), - } + }; // please pass one of apiKey, token, credentialsString & path as credentials - const credentials = { - token: "BEARER_TOKEN", // bearer token - } + const credentials: Credentials = { + token: 'BEARER_TOKEN', // bearer token + }; + + const primaryVaultConfig: VaultConfig = { + vaultId: 'VAULT_ID1', // primary vault + clusterId: 'CLUSTER_ID1', // ID from your vault URL Eg https://{clusterId}.vault.skyflowapis.com + env: Env.PROD, // Env by default it is set to PROD + credentials: credentials, // individual credentials + }; - const skyflowClient = new Skyflow({ + const skyflowConfig: SkyflowConfig = { vaultConfigs: [ - { - vaultId: "VAULT_ID1", // primary vault - clusterId: "CLUSTER_ID1", // ID from your vault URL Eg https://{clusterId}.vault.skyflowapis.com - env: Env.PROD, // Env by default it is set to PROD - credentials: credentials // individual credentials - } + primaryVaultConfig, ], skyflowCredentials: skyflowCredentials, // skyflow credentials will be used if no individual credentials are passed - logLevel: LogLevel.ERROR // set log level by default it is set to PROD - }); + logLevel: LogLevel.ERROR, // set log level by default it is set to PROD + }; + + const skyflowClient: Skyflow = new Skyflow(skyflowConfig); + + const secondaryVaultConfig: VaultConfig = { + vaultId: 'VAULT_ID2', // secondary vault + clusterId: 'CLUSTER_ID2', // ID from your vault URL Eg https://{clusterId}.vault.skyflowapis.com + env: Env.PROD, // Env by default it is set to PROD + // if you dont specify individual credentials, skyflow credentials will be used + }; //add vault config from prod env - skyflowClient.addVaultConfig( - { - vaultId: "VAULT_ID2", // secondary vault - clusterId: "CLUSTER_ID2", // ID from your vault URL Eg https://{clusterId}.vault.skyflowapis.com - env: Env.PROD, // Env by default it is set to PROD - // if you dont specify individual credentials, skyflow credentials will be used - } - ); + skyflowClient.addVaultConfig(secondaryVaultConfig); //perform operations - const getIds = [ - "SKYLFOW_ID1", - "SKYLFOW_ID2" - ] + const getIds: Array = [ + 'SKYLFOW_ID1', + 'SKYLFOW_ID2', + ]; - const getRequest = new GetRequest( - "TABLE_NAME", - getIds + const tableName: string = 'TABLE_NAME'; + + const getRequest: GetRequest = new GetRequest( + tableName, + getIds, ); //perform delete call if you dont specify vault() it will return the first valid vault - skyflowClient.vault("VAULT_ID1").get(getRequest) + skyflowClient.vault('VAULT_ID1').get(getRequest) .then(response => { - // + // get response const getResponse: GetResponse = response as GetResponse; console.log(getResponse.data); - const insertData = getResponse.data; + const insertData: Array = getResponse.data!; + + const tableName: string = 'TABLE_NAME'; //parse insertData to remove skyflow_id //get data from one vault and insert data to another vault - const insertRequest = new InsertRequest( - "TABLE_NAME", - insertData!, + const insertRequest: InsertRequest = new InsertRequest( + tableName, + insertData, ); - skyflowClient.vault("VAULT_ID2").insert( + skyflowClient.vault('VAULT_ID2').insert( insertRequest - ).then(resp => { + ).then((resp: InsertResponse) => { console.log(resp); - }).catch(err => { + }).catch((err: SkyflowError) => { console.log(JSON.stringify(err)); }); }) - .catch(err => { + .catch((err: SkyflowError) => { console.log(JSON.stringify(err)); }); } catch (err) { diff --git a/samples/vault-api/delete-records.ts b/samples/vault-api/delete-records.ts index d2d3cad..d81f0c6 100644 --- a/samples/vault-api/delete-records.ts +++ b/samples/vault-api/delete-records.ts @@ -1,8 +1,8 @@ -import { DeleteRequest, Env, LogLevel, Skyflow } from "skyflow-node"; +import { Credentials, DeleteRequest, DeleteResponse, Env, LogLevel, Skyflow, SkyflowConfig, VaultConfig, SkyflowError } from 'skyflow-node'; try { // To generate Bearer Token from credentials string. - const cred = { + const cred: Object = { clientID: '', clientName: '', keyID: '', @@ -11,45 +11,51 @@ try { }; // please pass one of apiKey, token, credentialsString & path as credentials - const skyflowCredentials = { - credentialsString: JSON.stringify(cred) - } + const skyflowCredentials: Credentials = { + credentialsString: JSON.stringify(cred), + }; // please pass one of apiKey, token, credentialsString & path as credentials - const credentials = { - apiKey: "API_KEY", // API Key - } + const credentials: Credentials = { + apiKey: 'API_KEY', // API Key + }; + + const primaryVaultConfig: VaultConfig = { + vaultId: 'VAULT_ID', // primary vault + clusterId: 'CLUSTER_ID', // ID from your vault URL Eg https://{clusterId}.vault.skyflowapis.com + env: Env.PROD, // Env by default it is set to PROD + credentials: credentials, // individual credentials + }; - const skyflowClient = new Skyflow({ + const skyflowConfig: SkyflowConfig = { vaultConfigs: [ - { - vaultId: "VAULT_ID", // primary vault - clusterId: "CLUSTER_ID", // ID from your vault URL Eg https://{clusterId}.vault.skyflowapis.com - env: Env.PROD, // Env by default it is set to PROD - credentials: credentials // individual credentials - } + primaryVaultConfig, ], skyflowCredentials: skyflowCredentials, // skyflow credentials will be used if no individual credentials are passed - logLevel: LogLevel.ERROR // set log level by default it is set to PROD - }); + logLevel: LogLevel.ERROR, // set log level by default it is set to PROD + }; - const deleteIds = [ + const skyflowClient: Skyflow = new Skyflow(skyflowConfig); + + const deleteIds: Array = [ 'SKYFLOW_ID1', 'SKYFLOW_ID2', 'SKYFLOW_ID3', - ] + ]; + + const tableName: string = 'TABLE_NAME'; // TABLE_NAME - const deleteRequest = new DeleteRequest( - "TABLE_NAME", // TABLE_NAME - deleteIds + const deleteRequest: DeleteRequest = new DeleteRequest( + tableName, + deleteIds, ); // will return first Vault ID skyflowClient.vault().delete( - deleteRequest - ).then(resp => { + deleteRequest, + ).then((resp: DeleteResponse) => { console.log(resp); - }).catch(err => { + }).catch((err: SkyflowError) => { console.log(JSON.stringify(err)); }); } catch (err) { diff --git a/samples/vault-api/detokenzie-records.ts b/samples/vault-api/detokenzie-records.ts index 9ce291e..3349a45 100644 --- a/samples/vault-api/detokenzie-records.ts +++ b/samples/vault-api/detokenzie-records.ts @@ -1,8 +1,8 @@ -import { DetokenizeOptions, DetokenizeRequest, Env, LogLevel, RedactionType, Skyflow } from "skyflow-node"; +import { Credentials, DetokenizeOptions, DetokenizeRequest, DetokenizeResponse, Env, LogLevel, RedactionType, Skyflow, SkyflowError, VaultConfig, SkyflowConfig } from 'skyflow-node'; try { // To generate Bearer Token from credentials string. - const cred = { + const cred: Object = { clientID: '', clientName: '', keyID: '', @@ -11,53 +11,59 @@ try { }; // please pass one of apiKey, token, credentialsString & path as credentials - const skyflowCredentials = { - credentialsString: JSON.stringify(cred) - } + const skyflowCredentials: Credentials = { + credentialsString: JSON.stringify(cred), + }; // please pass one of apiKey, token, credentialsString & path as credentials - const credentials = { - token: "TOKEN", // bearer token - } + const credentials: Credentials = { + token: 'TOKEN', // bearer token + }; - const skyflowClient = new Skyflow({ + const primaryVaultConfig: VaultConfig = { + vaultId: 'VAULT_ID', // primary vault + clusterId: 'CLUSTER_ID', // ID from your vault URL Eg https://{clusterId}.vault.skyflowapis.com + env: Env.PROD, // Env by default it is set to PROD + credentials: credentials, // individual credentials + }; + + const skyflowConfig: SkyflowConfig = { vaultConfigs: [ - { - vaultId: "VAULT_ID", // primary vault - clusterId: "CLUSTER_ID", // ID from your vault URL Eg https://{clusterId}.vault.skyflowapis.com - env: Env.PROD, // Env by default it is set to PROD - credentials: credentials // individual credentials - } + primaryVaultConfig, ], skyflowCredentials: skyflowCredentials, // skyflow credentials will be used if no individual credentials are passed - logLevel: LogLevel.ERROR // set log level by default it is set to PROD - }); + logLevel: LogLevel.ERROR, // set log level by default it is set to PROD + }; + + const skyflowClient: Skyflow = new Skyflow(skyflowConfig); - const detokenizeData = [ + const detokenizeData: Array = [ 'TOKEN1', 'TOKEN2', - 'TOKEN3' - ] + 'TOKEN3', + ]; - const detokenizeRequest = new DetokenizeRequest( + const redactionType: RedactionType = RedactionType.REDACTED; + + const detokenizeRequest: DetokenizeRequest = new DetokenizeRequest( detokenizeData, - RedactionType.REDACTED - ) + redactionType, + ); - const detokenizeOptions = new DetokenizeOptions() + const detokenizeOptions: DetokenizeOptions = new DetokenizeOptions(); // options can be set using setters detokenizeOptions.setContinueOnError(true); detokenizeOptions.setDownloadURL(false); - skyflowClient.vault("VAULT_ID").detokenize( + skyflowClient.vault('VAULT_ID').detokenize( detokenizeRequest, detokenizeOptions - ).then(response => { + ).then((response: DetokenizeResponse) => { console.log(response); - }).catch(error => { + }).catch((error: SkyflowError) => { console.log(JSON.stringify(error)); - }) + }); } catch (err) { console.log(JSON.stringify(err)); diff --git a/samples/vault-api/file-upload.ts b/samples/vault-api/file-upload.ts index 476d581..a51441e 100644 --- a/samples/vault-api/file-upload.ts +++ b/samples/vault-api/file-upload.ts @@ -1,9 +1,9 @@ //please use node version 18 & above to run file upload -import { Env, FileUploadRequest, LogLevel, Skyflow } from "skyflow-node"; +import { Credentials, Env, FileUploadRequest, FileUploadResponse, LogLevel, Skyflow, SkyflowConfig, VaultConfig, SkyflowError } from 'skyflow-node'; try { // To generate Bearer Token from credentials string. - const cred = { + const cred: Object = { clientID: '', clientName: '', keyID: '', @@ -12,40 +12,49 @@ try { }; // please pass one of apiKey, token, credentialsString & path as credentials - const skyflowCredentials = { + const skyflowCredentials: Credentials = { credentialsString: JSON.stringify(cred), - } + }; // please pass one of apiKey, token, credentialsString & path as credentials - const credentials = { - path: "PATH_TO_CREDENTIALS_JSON", // path to credentials file - } + const credentials: Credentials = { + path: 'PATH_TO_CREDENTIALS_JSON', // path to credentials file + }; + + const primaryVaultConfig: VaultConfig = { + vaultId: 'VAULT_ID', // primary vault + clusterId: 'CLUSTER_ID', // ID from your vault URL Eg https://{clusterId}.vault.skyflowapis.com + env: Env.PROD, // Env by default it is set to PROD + credentials: credentials, // individual credentials + }; - const skyflowClient = new Skyflow({ + const skyflowConfig: SkyflowConfig = { vaultConfigs: [ - { - vaultId: "VAULT_ID", // primary vault - clusterId: "CLUSTER_ID", // ID from your vault URL Eg https://{clusterId}.vault.skyflowapis.com - env: Env.PROD, // Env by default it is set to PROD - credentials: credentials // individual credentials - } + primaryVaultConfig, ], skyflowCredentials: skyflowCredentials, // skyflow credentials will be used if no individual credentials are passed - logLevel: LogLevel.ERROR // set log level by default it is set to PROD - }); + logLevel: LogLevel.ERROR, // set log level by default it is set to PROD + }; + + const skyflowClient: Skyflow = new Skyflow(skyflowConfig); + + const tableName: string = 'TABLE_NAME'; //table name + const skyflowId: string = 'SKYFLOW_ID'; //skyflow id + const columnName: string = 'COLUMN_NAME'; //column name + const filePath: string = 'FILE_PATH'; //file path - const uploadReq = new FileUploadRequest( - "TABLE_NAME", - "SKYFLOW_ID", - "COLUMN_NAME", - "FILE_PATH" + const uploadReq: FileUploadRequest = new FileUploadRequest( + tableName, + skyflowId, + columnName, + filePath, ); - skyflowClient.vault("VAULT_ID").uploadFile( - uploadReq - ).then(response => { + skyflowClient.vault('VAULT_ID').uploadFile( + uploadReq, + ).then((response: FileUploadResponse) => { console.log(response); - }).catch(error => { + }).catch((error: SkyflowError) => { console.log(JSON.stringify(error)); }); } catch (err) { diff --git a/samples/vault-api/get-column-values.ts b/samples/vault-api/get-column-values.ts index 8d004dd..1ea9b0a 100644 --- a/samples/vault-api/get-column-values.ts +++ b/samples/vault-api/get-column-values.ts @@ -1,8 +1,8 @@ -import { Env, GetOptions, LogLevel, Skyflow, GetColumnRequest } from "skyflow-node"; +import { Env, GetOptions, LogLevel, Skyflow, GetColumnRequest, Credentials, SkyflowConfig, VaultConfig, GetResponse, SkyflowError } from 'skyflow-node'; try { // To generate Bearer Token from credentials string. - const cred = { + const cred: Object = { clientID: '', clientName: '', keyID: '', @@ -11,49 +11,56 @@ try { }; // please pass one of apiKey, token, credentialsString & path as credentials - const skyflowCredentials = { + const skyflowCredentials: Credentials = { credentialsString: JSON.stringify(cred), - } + }; // please pass one of apiKey, token, credentialsString & path as credentials - const credentials = { - path: "PATH_TO_CREDENTIALS_JSON", // path to credentials file - } + const credentials: Credentials = { + path: 'PATH_TO_CREDENTIALS_JSON', // path to credentials file + }; + + const primaryVaultConfig: VaultConfig = { + vaultId: 'VAULT_ID', // primary vault + clusterId: 'CLUSTER_ID', // ID from your vault URL Eg https://{clusterId}.vault.skyflowapis.com + env: Env.PROD, // Env by default it is set to PROD + credentials: credentials, // individual credentials + }; - const skyflowClient = new Skyflow({ + const skyflowConfig: SkyflowConfig = { vaultConfigs: [ - { - vaultId: "VAULT_ID", // primary vault - clusterId: "CLUSTER_ID", // ID from your vault URL Eg https://{clusterId}.vault.skyflowapis.com - env: Env.PROD, // Env by default it is set to PROD - credentials: credentials // individual credentials - } + primaryVaultConfig, ], skyflowCredentials: skyflowCredentials, // skyflow credentials will be used if no individual credentials are passed - logLevel: LogLevel.ERROR // set log level by default it is set to PROD - }); + logLevel: LogLevel.ERROR, // set log level by default it is set to PROD + }; - const columnValues = [ + const skyflowClient: Skyflow = new Skyflow(skyflowConfig); + + const columnValues: Array = [ 'VALUE1', 'VALUE2', - ] + ]; + + const tableName: string = 'TABLE_NAME'; + const columnName: string = 'COLUMN_NAME'; //Name of the column. It must be configured as unique in the schema. - const getRequest = new GetColumnRequest( - "TABLE_NAME", - "COLUMN_NAME", //Name of the column. It must be configured as unique in the schema. - columnValues //Column values of the records to return - ) + const getRequest: GetColumnRequest = new GetColumnRequest( + tableName, + columnName, + columnValues, //Column values of the records to return + ); - const getOptions = new GetOptions() + const getOptions: GetOptions = new GetOptions(); //use setters of setting options refer to skyflow docs for more options getOptions.setReturnTokens(true); - skyflowClient.vault("VAULT_ID").get( + skyflowClient.vault('VAULT_ID').get( getRequest, - getOptions - ).then(response => { + getOptions, + ).then((response: GetResponse) => { console.log(response); - }).catch(error => { + }).catch((error: SkyflowError) => { console.log(JSON.stringify(error)); }); } catch (err) { diff --git a/samples/vault-api/get-records.ts b/samples/vault-api/get-records.ts index 0cbcced..260eafe 100644 --- a/samples/vault-api/get-records.ts +++ b/samples/vault-api/get-records.ts @@ -1,8 +1,8 @@ -import { Env, GetOptions, GetRequest, LogLevel, Skyflow } from "skyflow-node"; +import { Credentials, Env, GetOptions, GetRequest, GetResponse, LogLevel, Skyflow, SkyflowError, SkyflowConfig, VaultConfig } from 'skyflow-node'; try { // To generate Bearer Token from credentials string. - const cred = { + const cred: Object = { clientID: '', clientName: '', keyID: '', @@ -11,48 +11,54 @@ try { }; // please pass one of apiKey, token, credentialsString & path as credentials - const skyflowCredentials = { + const skyflowCredentials: Credentials = { credentialsString: JSON.stringify(cred), - } + }; // please pass one of apiKey, token, credentialsString & path as credentials - const credentials = { - path: "PATH_TO_CREDENTIALS_JSON", // path to credentials file - } + const credentials: Credentials = { + path: 'PATH_TO_CREDENTIALS_JSON', // path to credentials file + }; + + const primaryVaultConfig: VaultConfig = { + vaultId: 'VAULT_ID', // primary vault + clusterId: 'CLUSTER_ID', // ID from your vault URL Eg https://{clusterId}.vault.skyflowapis.com + env: Env.PROD, // Env by default it is set to PROD + credentials: credentials, // individual credentials + }; - const skyflowClient = new Skyflow({ + const skyflowConfig: SkyflowConfig = { vaultConfigs: [ - { - vaultId: "VAULT_ID", // primary vault - clusterId: "CLUSTER_ID", // ID from your vault URL Eg https://{clusterId}.vault.skyflowapis.com - env: Env.PROD, // Env by default it is set to PROD - credentials: credentials // individual credentials - } + primaryVaultConfig, ], skyflowCredentials: skyflowCredentials, // skyflow credentials will be used if no individual credentials are passed - logLevel: LogLevel.ERROR // set log level by default it is set to PROD - }); + logLevel: LogLevel.ERROR, // set log level by default it is set to PROD + }; - const getIds = [ + const skyflowClient: Skyflow = new Skyflow(skyflowConfig); + + const getIds: Array = [ 'SKYFLOW_ID1', 'SKYFLOW_ID2', - ] + ]; + + const tableName: string = 'TABLE_NAME'; - const getRequest = new GetRequest( - "TABLE_NAME", - getIds - ) + const getRequest: GetRequest = new GetRequest( + tableName, + getIds, + ); - const getOptions = new GetOptions() + const getOptions: GetOptions = new GetOptions(); //use setters of setting options refer to skyflow docs for more options getOptions.setReturnTokens(true); - skyflowClient.vault("VAULT_ID").get( + skyflowClient.vault('VAULT_ID').get( getRequest, getOptions - ).then(response => { + ).then((response: GetResponse) => { console.log(response); - }).catch(error => { + }).catch((error: SkyflowError) => { console.log(JSON.stringify(error)); }); } catch (err) { diff --git a/samples/vault-api/insert-byot.ts b/samples/vault-api/insert-byot.ts index 2668507..a00493a 100644 --- a/samples/vault-api/insert-byot.ts +++ b/samples/vault-api/insert-byot.ts @@ -1,8 +1,8 @@ -import { BYOT, Env, InsertOptions, InsertRequest, LogLevel, Skyflow } from "skyflow-node"; +import { BYOT, Credentials, Env, InsertOptions, InsertRequest, LogLevel, Skyflow, VaultConfig, SkyflowConfig, InsertResponse, SkyflowError } from 'skyflow-node'; try { // To generate Bearer Token from credentials string. - const cred = { + const cred: Object = { clientID: '', clientName: '', keyID: '', @@ -11,55 +11,63 @@ try { }; // please pass one of apiKey, token, credentialsString & path as credentials - const skyflowCredentials = { + const skyflowCredentials: Credentials = { credentialsString: JSON.stringify(cred), - } + }; // please pass one of apiKey, token, credentialsString & path as credentials - const credentials = { + const credentials: Credentials = { token: "BEARER", // token - } + }; + + const primaryVaultConfig: VaultConfig = { + vaultId: "VAULT_ID", // primary vault + clusterId: "CLUSTER_ID", // ID from your vault URL Eg https://{clusterId}.vault.skyflowapis.com + env: Env.PROD, // Env by default it is set to PROD + credentials: credentials, // individual credentials + }; - const skyflowClient = new Skyflow({ + const skyflowConfig: SkyflowConfig = { vaultConfigs: [ - { - vaultId: "VAULT_ID", // primary vault - clusterId: "CLUSTER_ID", // ID from your vault URL Eg https://{clusterId}.vault.skyflowapis.com - env: Env.PROD, // Env by default it is set to PROD - credentials: credentials // individual credentials - } + primaryVaultConfig, ], skyflowCredentials: skyflowCredentials, // skyflow credentials will be used if no individual credentials are passed - logLevel: LogLevel.INFO // set log level by default it is set to PROD - }); + logLevel: LogLevel.INFO, // set log level by default it is set to PROD + }; + + const skyflowClient: Skyflow = new Skyflow(skyflowConfig); //sample data - const insertData = [ + const insertData: Array = [ { card_number: 'CARD_NUMBER1', card_cvv: 'CVV1' }, { card_number: 'CARD_NUMBER2', card_cvv: 'CVV2' }, - ] + ]; + + const tableName: string = 'TABLE_NAME'; - const insertReq = new InsertRequest( - "TABLE_NAME", + const insertReq: InsertRequest = new InsertRequest( + tableName, insertData, - ) + ); - const insertOptions = new InsertOptions() + const tokens: Array = [ + { card_number: 'TOKEN1', card_cvv: 'TOKEN2' }, + { card_number: 'TOKEN3', card_cvv: 'TOKEN4' }, + ]; + + const insertOptions: InsertOptions = new InsertOptions() //use setters for setting options insertOptions.setReturnTokens(true); insertOptions.setTokenMode(BYOT.ENABLE); - insertOptions.setTokens([ - { card_number: 'TOKEN1', card_cvv: 'TOKEN2' }, - { card_number: 'TOKEN3', card_cvv: 'TOKEN4' } - ]); + insertOptions.setTokens(tokens); // insertOptions.setContinueOnError(true); // if continue on error is set true we will return requestIndex for errors - skyflowClient.vault("VAULT_ID").insert( + skyflowClient.vault('VAULT_ID').insert( insertReq, - insertOptions - ).then(resp => { + insertOptions, + ).then((resp: InsertResponse) => { console.log(resp); - }).catch(err => { + }).catch((err: SkyflowError) => { console.log(JSON.stringify(err)); }); } catch (err) { diff --git a/samples/vault-api/insert-records.ts b/samples/vault-api/insert-records.ts index 720e4c1..03f1809 100644 --- a/samples/vault-api/insert-records.ts +++ b/samples/vault-api/insert-records.ts @@ -1,60 +1,53 @@ -import { Env, InsertOptions, InsertRequest, LogLevel, Skyflow } from "skyflow-node"; +import { Credentials, Env, InsertOptions, InsertRequest, LogLevel, Skyflow, VaultConfig, SkyflowConfig, InsertResponse, SkyflowError } from 'skyflow-node'; try { - // To generate Bearer Token from credentials string. - const cred = { - clientID: '', - clientName: '', - keyID: '', - tokenURI: '', - privateKey: '', + // please pass one of apiKey, token, credentialsString & path as credentials + const credentials: Credentials = { + apiKey: 'API_KEY', // API Key }; - // please pass one of apiKey, token, credentialsString & path as credentials - const skyflowCredentials = { - credentialsString: JSON.stringify(cred), - } + const logLevel: LogLevel = LogLevel.INFO; - // please pass one of apiKey, token, credentialsString & path as credentials - const credentials = { - apiKey: "API_KEY", // API Key - } + const primaryVaultConfig: VaultConfig = { + vaultId: 'VAULT_ID', // primary vault + clusterId: 'CLUSTER_ID', // ID from your vault URL Eg https://{clusterId}.vault.skyflowapis.com + env: Env.PROD, // Env by default it is set to PROD + credentials: credentials, // individual credentials + }; - const skyflowClient = new Skyflow({ + const skyflowConfig: SkyflowConfig = { vaultConfigs: [ - { - vaultId: "VAULT_ID", // primary vault - clusterId: "CLUSTER_ID", // ID from your vault URL Eg https://{clusterId}.vault.skyflowapis.com - env: Env.PROD, // Env by default it is set to PROD - credentials: credentials // individual credentials - } + primaryVaultConfig, ], - skyflowCredentials: skyflowCredentials, // skyflow credentials will be used if no individual credentials are passed - logLevel: LogLevel.ERROR // set log level by default it is set to PROD - }); + logLevel: logLevel, // set log level by default it is set to PROD + }; + + const skyflowClient: Skyflow = new Skyflow(skyflowConfig); //sample data - const insertData = [ - { card_number: '4111111111111111', cvv: '1234' }, - { card_number: '42424242424242424', cvv: '321' }, - ] + const insertData: Array = [ + { card_number: '4111111111111111', card_cvv: '1234' }, + { card_number: '42424242424242424', card_cvv: '321' }, + ]; + + const tableName: string = 'TABLE_NAME'; - const insertReq = new InsertRequest( - "TABLE_NAME", + const insertReq: InsertRequest = new InsertRequest( + tableName, insertData, - ) + ); - const insertOptions = new InsertOptions() + const insertOptions: InsertOptions = new InsertOptions(); //use setters for setting options insertOptions.setReturnTokens(true); // insertOptions.setContinueOnError(true); // if continue on error is set true we will return requestIndex for errors - skyflowClient.vault("VAULT_ID").insert( + skyflowClient.vault('VAULT_ID').insert( insertReq, insertOptions - ).then(resp => { + ).then((resp: InsertResponse) => { console.log(resp); - }).catch(err => { + }).catch((err: SkyflowError) => { console.log(JSON.stringify(err)); }); } catch (err) { diff --git a/samples/vault-api/invoke-connection.ts b/samples/vault-api/invoke-connection.ts index 92165fc..54f2a68 100644 --- a/samples/vault-api/invoke-connection.ts +++ b/samples/vault-api/invoke-connection.ts @@ -1,8 +1,8 @@ -import { Env, Skyflow, InvokeConnectionRequest, Method, LogLevel } from "skyflow-node"; +import { Env, Skyflow, InvokeConnectionRequest, RequestMethod, LogLevel, Credentials, SkyflowConfig, VaultConfig, ConnectionConfig, InvokeConnectionResponse, SkyflowError } from 'skyflow-node'; try { // To generate Bearer Token from credentials string. - const cred = { + const cred: Object = { clientID: '', clientName: '', keyID: '', @@ -11,58 +11,66 @@ try { }; // please pass one of apiKey, token, credentialsString & path as credentials - const skyflowCredentials = { + const skyflowCredentials: Credentials = { credentialsString: JSON.stringify(cred), - } + }; // please pass one of apiKey, token, credentialsString & path as credentials - const credentials = { - apiKey: "API_KEY", // API Key - } + const credentials: Credentials = { + apiKey: 'API_KEY', // API Key + }; + + const primaryVaultConfig: VaultConfig = { + vaultId: 'VAULT_ID', // primary vault ( NOTE : One vault is necessary) + clusterId: 'CLUSTER_ID', // ID from your vault URL Eg https://{clusterId}.vault.skyflowapis.com + env: Env.PROD, // Env by default it is set to PROD + credentials: credentials, // individual credentials + }; + + const primaryConnectionConfig: ConnectionConfig = { + connectionId: 'CONNECTION_ID', // get connection ID from https://${clusterId}.gateway.skyflowapis.dev/v1/gateway/inboundRoutes/${connectionId}/${connection_name} + connectionUrl: 'CONNECTION_URL', // the whole URL https://${clusterId}.gateway.skyflowapis.dev/v1/gateway/inboundRoutes/${connectionId}/${connection_name} + credentials: credentials + }; - const skyflowClient = new Skyflow({ + const skyflowConfig: SkyflowConfig = { vaultConfigs: [ - { - vaultId: "VAULT_ID", // primary vault ( NOTE : One vault is necessary) - clusterId: "CLUSTER_ID", // ID from your vault URL Eg https://{clusterId}.vault.skyflowapis.com - env: Env.PROD, // Env by default it is set to PROD - credentials: credentials // individual credentials - } + primaryVaultConfig, ], connectionConfigs: [ - { - connectionId: "CONNECTION_ID", // get connection ID from https://${clusterId}.gateway.skyflowapis.dev/v1/gateway/inboundRoutes/${connectionId}/${connection_name} - connectionUrl: "CONNECTION_URL", // the whole URL https://${clusterId}.gateway.skyflowapis.dev/v1/gateway/inboundRoutes/${connectionId}/${connection_name} - credentials: credentials - } + primaryConnectionConfig, ], skyflowCredentials: skyflowCredentials, // skyflow credentials will be used if no individual credentials are passed logLevel: LogLevel.ERROR // set log level by default it is set to PROD - }); + }; + + const skyflowClient: Skyflow = new Skyflow(skyflowConfig); const body = { - "KEY1": "VALUE1", - "KEY2": "VALUE2", + 'KEY1': 'VALUE1', + 'KEY2': 'VALUE2', }; const headers = { 'Content-Type': 'application/json', }; - const invokeReq = new InvokeConnectionRequest( - Method.POST, + const method: RequestMethod = RequestMethod.POST; + + const invokeReq: InvokeConnectionRequest = new InvokeConnectionRequest( + method, body, - headers + headers, ); //will return the first connection skyflowClient.connection().invoke( - invokeReq - ).then(resp => { + invokeReq, + ).then((resp: InvokeConnectionResponse) => { console.log(resp); - }).catch(err => { + }).catch((err: SkyflowError) => { console.log(JSON.stringify(err)); - }) + }); } catch (err) { console.log(JSON.stringify(err)); } \ No newline at end of file diff --git a/samples/vault-api/query-records.ts b/samples/vault-api/query-records.ts index cb9e10c..3f0736e 100644 --- a/samples/vault-api/query-records.ts +++ b/samples/vault-api/query-records.ts @@ -1,7 +1,7 @@ -import { Env, LogLevel, QueryRequest, Skyflow } from "skyflow-node"; +import { Credentials, Env, LogLevel, QueryRequest, QueryResponse, Skyflow, SkyflowConfig, SkyflowError, VaultConfig } from 'skyflow-node'; try { // To generate Bearer Token from credentials string. - const cred = { + const cred: Object = { clientID: '', clientName: '', keyID: '', @@ -10,39 +10,43 @@ try { }; // please pass one of apiKey, token, credentialsString & path as credentials - const skyflowCredentials = { + const skyflowCredentials: Credentials = { credentialsString: JSON.stringify(cred), - } + }; // please pass one of apiKey, token, credentialsString & path as credentials - const credentials = { - apiKey: "API_KEY", // API key - } + const credentials: Credentials = { + apiKey: 'API_KEY', // API key + }; + + const primaryVaultConfig: VaultConfig = { + vaultId: 'VAULT_ID', // primary vault + clusterId: 'CLUSTER_ID', // ID from your vault URL Eg https://{clusterId}.vault.skyflowapis.com + env: Env.PROD, // Env by default it is set to PROD + credentials: credentials, // individual credentials + }; - const skyflowClient = new Skyflow({ + const skyflowConfig: SkyflowConfig = { vaultConfigs: [ - { - vaultId: "VAULT_ID", // primary vault - clusterId: "CLUSTER_ID", // ID from your vault URL Eg https://{clusterId}.vault.skyflowapis.com - env: Env.PROD, // Env by default it is set to PROD - credentials: credentials // individual credentials - } + primaryVaultConfig, ], skyflowCredentials: skyflowCredentials, // skyflow credentials will be used if no individual credentials are passed - logLevel: LogLevel.ERROR // set log level by default it is set to PROD - }); + logLevel: LogLevel.ERROR, // set log level by default it is set to PROD + }; + + const skyflowClient: Skyflow = new Skyflow(skyflowConfig); //sample query - const query = "select * from TABLE_NAME limit 1"; + const query: string = 'select * from TABLE_NAME limit 1'; - const queryReq = new QueryRequest( - query + const queryReq: QueryRequest = new QueryRequest( + query, ); - skyflowClient.vault("VAULT_ID").query( + skyflowClient.vault('VAULT_ID').query( queryReq, - ).then(resp => { + ).then((resp: QueryResponse) => { console.log(resp); - }).catch(err => { + }).catch((err: SkyflowError) => { console.log(JSON.stringify(err)); }); } catch (err) { diff --git a/samples/vault-api/tokenize-records.ts b/samples/vault-api/tokenize-records.ts index 75e049b..82bce25 100644 --- a/samples/vault-api/tokenize-records.ts +++ b/samples/vault-api/tokenize-records.ts @@ -1,7 +1,7 @@ -import { Env, LogLevel, Skyflow, TokenizeRequest } from "skyflow-node"; +import { Credentials, Env, LogLevel, Skyflow, SkyflowConfig, TokenizeRequest, VaultConfig, TokenizeRequestType, TokenizeResponse, SkyflowError } from 'skyflow-node'; try { // To generate Bearer Token from credentials string. - const cred = { + const cred: Object = { clientID: '', clientName: '', keyID: '', @@ -10,44 +10,48 @@ try { }; // please pass one of apiKey, token, credentialsString & path as credentials - const skyflowCredentials = { + const skyflowCredentials: Credentials = { credentialsString: JSON.stringify(cred), - } + }; // please pass one of apiKey, token, credentialsString & path as credentials - const credentials = { - apiKey: "API_KEY", // API key - } + const credentials: Credentials = { + apiKey: 'API_KEY', // API key + }; + + const primaryVaultConfig: VaultConfig = { + vaultId: 'VAULT_ID', // primary vault + clusterId: 'CLUSTER_ID', // ID from your vault URL Eg https://{clusterId}.vault.skyflowapis.com + env: Env.PROD, // Env by default it is set to PROD + credentials: credentials, // individual credentials + }; - const skyflowClient = new Skyflow({ + const skyflowConfig: SkyflowConfig = { vaultConfigs: [ - { - vaultId: "VAULT_ID", // primary vault - clusterId: "CLUSTER_ID", // ID from your vault URL Eg https://{clusterId}.vault.skyflowapis.com - env: Env.PROD, // Env by default it is set to PROD - credentials: credentials // individual credentails - } + primaryVaultConfig, ], skyflowCredentials: skyflowCredentials, // skyflow credentials will be used if no individual credentials are passed logLevel: LogLevel.ERROR // set log level by default it is set to PROD - }); + }; + + const skyflowClient: Skyflow = new Skyflow(skyflowConfig); // tokenize only supports value and columngroup // sample data - const tokenizeValues = [ + const tokenizeValues: Array = [ { value: '4111111111111111', columnGroup: 'card_number_cg' }, { value: '42424242424242424', columnGroup: 'card_number_cg' } ]; - const tokenReq = new TokenizeRequest( - tokenizeValues + const tokenReq: TokenizeRequest = new TokenizeRequest( + tokenizeValues, ); - skyflowClient.vault("VAULT_ID").tokenize( + skyflowClient.vault('VAULT_ID').tokenize( tokenReq, - ).then(resp => { + ).then((resp: TokenizeResponse) => { console.log(resp); - }).catch(err => { + }).catch((err: SkyflowError) => { console.log(JSON.stringify(err)); }); } catch (err) { diff --git a/samples/vault-api/update-record.ts b/samples/vault-api/update-record.ts index 1168262..f06bc6e 100644 --- a/samples/vault-api/update-record.ts +++ b/samples/vault-api/update-record.ts @@ -1,8 +1,8 @@ -import { Env, Skyflow, UpdateRequest, UpdateOptions, LogLevel } from "skyflow-node"; +import { Env, Skyflow, UpdateRequest, UpdateOptions, LogLevel, Credentials, VaultConfig, SkyflowConfig, UpdateResponse, SkyflowError } from 'skyflow-node'; try { // To generate Bearer Token from credentials string. - const cred = { + const cred: Object = { clientID: '', clientName: '', keyID: '', @@ -11,49 +11,54 @@ try { }; // please pass one of apiKey, token, credentialsString & path as credentials - const skyflowCredentials = { + const skyflowCredentials: Credentials = { credentialsString: JSON.stringify(cred), - } + }; // please pass one of apiKey, token, credentialsString & path as credentials - const credentials = { - apiKey: "API_KEY", // API key - } + const credentials: Credentials = { + apiKey: 'API_KEY', // API key + }; + + const primaryVaultConfig: VaultConfig = { + vaultId: 'VAULT_ID', // primary vault + clusterId: 'CLUSTER_ID', // ID from your vault URL Eg https://{clusterId}.vault.skyflowapis.com + env: Env.PROD, // Env by default it is set to PROD + credentials: credentials, // individual credentials + }; - const skyflowClient = new Skyflow({ + const skyflowConfig: SkyflowConfig = { vaultConfigs: [ - { - vaultId: "VAULT_ID", // primary vault - clusterId: "CLUSTER_ID", // ID from your vault URL Eg https://{clusterId}.vault.skyflowapis.com - env: Env.PROD, // Env by default it is set to PROD - credentials: credentials // individual credentials - } + primaryVaultConfig, ], skyflowCredentials: skyflowCredentials, // skyflow credentials will be used if no individual credentials are passed - logLevel: LogLevel.ERROR // set log level by default it is set to PROD - }); + logLevel: LogLevel.ERROR, // set log level by default it is set to PROD + }; + + const skyflowClient: Skyflow = new Skyflow(skyflowConfig); + + const skyflowId: string = 'SKYFLOW_ID'; // sample data - const updateData = { card_number: '12333333333333444444' }; + const updateData: Object = { skyflowId, card_number: '12333333333333444444' }; - const skyflowId = "SKYFLOW_ID"; + const tableName: string = 'TABLE_NAME'; - const updateReq = new UpdateRequest( - "TABLE_NAME", - skyflowId, - updateData - ) + const updateReq: UpdateRequest = new UpdateRequest( + tableName, + updateData, + ); - const updateOptions = new UpdateOptions() + const updateOptions: UpdateOptions = new UpdateOptions(); updateOptions.setReturnTokens(true); - skyflowClient.vault("VAULT_ID").update( + skyflowClient.vault('VAULT_ID').update( updateReq, - updateOptions - ).then(resp => { + updateOptions, + ).then((resp: UpdateResponse) => { console.log(resp); - }).catch(err => { + }).catch((err: SkyflowError) => { console.log(JSON.stringify(err)); }); } catch (err) { diff --git a/src/error/index.ts b/src/error/index.ts index 3075065..a30a5d4 100644 --- a/src/error/index.ts +++ b/src/error/index.ts @@ -1,4 +1,4 @@ -import { ISkyflowError, parameterizedString } from "../utils"; +import { BAD_REQUEST, ISkyflowError, parameterizedString } from "../utils"; class SkyflowError extends Error { @@ -6,7 +6,7 @@ class SkyflowError extends Error { constructor(errorCode: ISkyflowError, args: any[] = []) { const formattedError = { - http_status: errorCode?.http_status || null, + http_status: errorCode?.http_status || BAD_REQUEST, details: errorCode?.details || null, request_ID: errorCode?.request_ID || null, grpc_code: errorCode?.grpc_code || null, diff --git a/src/index.ts b/src/index.ts index c154578..22fcbbd 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,5 +1,5 @@ import Skyflow from './vault/skyflow'; -import { LogLevel, Env, RedactionType, Method, OrderByEnum, BYOT } from './utils'; +import { LogLevel, Env, RedactionType, RequestMethod, OrderByEnum, BYOT } from './utils'; import InsertRequest from './vault/model/request/insert'; import InsertOptions from './vault/model/options/insert'; import GetRequest from './vault/model/request/get'; @@ -26,12 +26,21 @@ import UpdateResponse from './vault/model/response/update'; import FileUploadResponse from './vault/model/response/file-upload'; import QueryResponse from './vault/model/response/query'; import InvokeConnectionResponse from './vault/model/response/invoke/invoke'; +import { SkyflowConfig, TokenizeRequestType } from './vault/types'; +import VaultConfig from './vault/config/vault'; +import SkyflowError from './error'; +import ConnectionConfig from './vault/config/connection'; export { Env, LogLevel, - Method, + RequestMethod, Skyflow, + SkyflowConfig, + ConnectionConfig, + VaultConfig, + SkyflowError, + TokenizeRequestType, BearerTokenOptions, SignedDataTokensOptions, GenerateTokenOptions, diff --git a/src/service-account/index.ts b/src/service-account/index.ts index b60ce35..e31c3f4 100644 --- a/src/service-account/index.ts +++ b/src/service-account/index.ts @@ -94,7 +94,7 @@ function getToken(credentials, options?: BearerTokenOptions): Promise expiryTime) { + printLog(logs.infoLogs.BEARER_TOKEN_EXPIRED, MessageType.LOG); + isJwtExpired = true; + } + return isJwtExpired; + } catch (err) { + return true; } - let isJwtExpired = false; - const decoded: JwtPayload = jwt_decode(token); - const currentTime = (new Date().getTime() / 1000); - const expiryTime = decoded.exp; - if (expiryTime && currentTime > expiryTime) { - printLog(logs.infoLogs.BEARER_TOKEN_EXPIRED, MessageType.LOG); - isJwtExpired = true; - } - return isJwtExpired; } function isTokenValid(token: string) { + try { if (token === "") return false let isJwtExpired = false; const decoded: JwtPayload = jwt_decode(token); @@ -28,6 +33,9 @@ function isTokenValid(token: string) { isJwtExpired = true; } return !isJwtExpired; + } catch (err) { + return false; + } }; export { isExpired, isTokenValid }; \ No newline at end of file diff --git a/src/utils/logs/index.ts b/src/utils/logs/index.ts index cf7cdf6..3b4211a 100644 --- a/src/utils/logs/index.ts +++ b/src/utils/logs/index.ts @@ -63,6 +63,8 @@ const logs = { UNABLE_TO_GENERATE_SDK_METRIC: 'Unable to generate %s1 metric.', USING_BEARER_TOKEN: 'Using token from credentials', USING_API_KEY: 'Using api key from credentials', + USING_CREDENTIALS_STRING: 'Using credentials string from credentials', + USING_PATH: 'Using path from credentials', USING_SKYFLOW_CREDENTIALS_ENV: 'Using SKYFLOW_CREDENTIALS from env' }, errorLogs: { diff --git a/src/utils/validations/index.ts b/src/utils/validations/index.ts index bc4072d..aab2377 100644 --- a/src/utils/validations/index.ts +++ b/src/utils/validations/index.ts @@ -1,4 +1,4 @@ -import { CONNECTION, CONNECTION_ID, Env, isValidURL, LogLevel, MessageType, Method, OrderByEnum, parameterizedString, printLog, RedactionType, VAULT, VAULT_ID } from ".."; +import { CONNECTION, CONNECTION_ID, Env, isValidURL, LogLevel, MessageType, RequestMethod, OrderByEnum, parameterizedString, printLog, RedactionType, SKYFLOW_ID, VAULT, VAULT_ID } from ".."; import { V1BYOT } from "../../ _generated_/rest"; import SkyflowError from "../../error"; import SKYFLOW_ERROR_CODE from "../../error/codes"; @@ -41,7 +41,7 @@ export function isOrderBy(value?: string): boolean { } export function isMethod(value?: string): boolean { - return value !== undefined && Object.values(Method).includes(value as Method); + return value !== undefined && Object.values(RequestMethod).includes(value as RequestMethod); } export function isLogLevel(value?: string): boolean { @@ -505,23 +505,24 @@ export const validateUpdateRequest = (updateRequest: UpdateRequest, updateOption throw new SkyflowError(SKYFLOW_ERROR_CODE.INVALID_TABLE_NAME); } - if (!updateRequest?.skyflowId || !Object.prototype.hasOwnProperty.call(updateRequest, '_skyflowId')) { + if (!updateRequest.data) { + throw new SkyflowError(SKYFLOW_ERROR_CODE.EMPTY_UPDATE_DATA); + } + if (typeof updateRequest.data !== 'object') { + throw new SkyflowError(SKYFLOW_ERROR_CODE.INVALID_TYPE_OF_UPDATE_DATA); + } + + if (updateRequest?.data && !Object.prototype.hasOwnProperty.call(updateRequest.data, SKYFLOW_ID)) { printLog(logs.errorLogs.EMPTY_SKYFLOW_ID_IN_UPDATE, MessageType.ERROR, logLevel); throw new SkyflowError(SKYFLOW_ERROR_CODE.MISSING_SKYFLOW_ID_IN_UPDATE); } - if (typeof updateRequest.skyflowId !== 'string' || updateRequest.skyflowId.trim().length === 0) { + if (updateRequest?.data[SKYFLOW_ID] && typeof updateRequest.data[SKYFLOW_ID] !== 'string' || updateRequest.data[SKYFLOW_ID].trim().length === 0) { printLog(logs.errorLogs.INVALID_SKYFLOW_ID_IN_UPDATE, MessageType.ERROR, logLevel); throw new SkyflowError(SKYFLOW_ERROR_CODE.INVALID_SKYFLOW_ID_IN_UPDATE); } - if (!updateRequest.updateData) { - throw new SkyflowError(SKYFLOW_ERROR_CODE.EMPTY_UPDATE_DATA); - } - if (typeof updateRequest.updateData !== 'object') { - throw new SkyflowError(SKYFLOW_ERROR_CODE.INVALID_TYPE_OF_UPDATE_DATA); - } - validateUpdateInput(updateRequest.updateData); + validateUpdateInput(updateRequest.data); validateUpdateOptions(updateOptions); } else { throw new SkyflowError(SKYFLOW_ERROR_CODE.INVALID_UPDATE_REQUEST); @@ -788,16 +789,16 @@ export const validateDeleteRequest = (deleteRequest: DeleteRequest, logLevel: Lo throw new SkyflowError(SKYFLOW_ERROR_CODE.INVALID_TABLE_NAME); } - if (!deleteRequest?.deleteIds) { + if (!deleteRequest?.ids) { printLog(logs.errorLogs.EMPTY_IDS_IN_DELETE, MessageType.ERROR, logLevel); throw new SkyflowError(SKYFLOW_ERROR_CODE.EMPTY_DELETE_IDS) } - if (!Array.isArray(deleteRequest?.deleteIds)) { + if (!Array.isArray(deleteRequest?.ids)) { throw new SkyflowError(SKYFLOW_ERROR_CODE.INVALID_DELETE_IDS_INPUT) } - const deleteIds = deleteRequest?.deleteIds; + const deleteIds = deleteRequest?.ids; if (deleteIds.length === 0) { throw new SkyflowError(SKYFLOW_ERROR_CODE.EMPTY_DELETE_IDS); } diff --git a/src/vault/controller/connections/index.ts b/src/vault/controller/connections/index.ts index 9ad0872..7845699 100644 --- a/src/vault/controller/connections/index.ts +++ b/src/vault/controller/connections/index.ts @@ -1,10 +1,11 @@ //imports import axios from "axios"; -import { fillUrlWithPathAndQueryParams, generateSDKMetrics, getBearerToken, LogLevel, MessageType, Method, parameterizedString, printLog, SDK_METRICS_HEADER_KEY, SKYFLOW_AUTH_HEADER_KEY, REQUEST_ID_KEY, TYPES } from "../../../utils"; +import { fillUrlWithPathAndQueryParams, generateSDKMetrics, getBearerToken, LogLevel, MessageType, RequestMethod, parameterizedString, printLog, SDK_METRICS_HEADER_KEY, SKYFLOW_AUTH_HEADER_KEY, REQUEST_ID_KEY, TYPES } from "../../../utils"; import InvokeConnectionRequest from "../../model/request/inkove"; import logs from "../../../utils/logs"; import { validateInvokeConnectionRequest } from "../../../utils/validations"; import VaultClient from "../../client"; +import InvokeConnectionResponse from "../../model/response/invoke/invoke"; class ConnectionController { @@ -17,7 +18,7 @@ class ConnectionController { this.logLevel = client.getLogLevel(); } - invoke(invokeRequest: InvokeConnectionRequest) { + invoke(invokeRequest: InvokeConnectionRequest): Promise { return new Promise((resolve, reject) => { try { printLog(logs.infoLogs.INVOKE_CONNECTION_TRIGGERED, MessageType.LOG, this.logLevel); @@ -32,13 +33,17 @@ class ConnectionController { sdkHeaders[SDK_METRICS_HEADER_KEY] = JSON.stringify(generateSDKMetrics()); axios({ url: filledUrl, - method: invokeRequest.method || Method.POST, + method: invokeRequest.method || RequestMethod.POST, data: invokeRequest.body, headers: { ...invokeRequest.headers, ...sdkHeaders } }).then((response: any) => { printLog(logs.infoLogs.INVOKE_CONNECTION_REQUEST_RESOLVED, MessageType.LOG, this.logLevel); let requestId = response.headers[REQUEST_ID_KEY] - resolve({data: response.data, metadata: {requestId}}) + const invokeConnectionResponse = new InvokeConnectionResponse({ + data: response.data, + metadata: {requestId} + }); + resolve(invokeConnectionResponse); }).catch((err) => { printLog(logs.errorLogs.INVOKE_CONNECTION_REQUEST_REJECTED, MessageType.LOG, this.logLevel); this.client.failureResponse(err).catch((err)=>reject(err)) diff --git a/src/vault/controller/vault/index.ts b/src/vault/controller/vault/index.ts index b9a5224..64653a9 100644 --- a/src/vault/controller/vault/index.ts +++ b/src/vault/controller/vault/index.ts @@ -21,8 +21,8 @@ import QueryResponse from '../../model/response/query'; import FileUploadResponse from '../../model/response/file-upload'; import TokenizeResponse from '../../model/response/tokenize'; import TokenizeRequest from '../../model/request/tokenize'; -import { ParsedDetokenizeResponse, ParsedInsertBatchResponse, tokenizeRequestType } from '../../types'; -import { generateSDKMetrics, getBearerToken, MessageType, parameterizedString, printLog, TYPES, SDK_METRICS_HEADER_KEY, removeSDKVersion } from '../../../utils'; +import { ParsedDetokenizeResponse, ParsedInsertBatchResponse, TokenizeRequestType } from '../../types'; +import { generateSDKMetrics, getBearerToken, MessageType, parameterizedString, printLog, TYPES, SDK_METRICS_HEADER_KEY, removeSDKVersion, RedactionType, SKYFLOW_ID } from '../../../utils'; import GetColumnRequest from '../../model/request/get-column'; import logs from '../../../utils/logs'; import VaultClient from '../../client'; @@ -253,7 +253,9 @@ class VaultController { // Validation checks validateUpdateRequest(request, options, this.client.getLogLevel()); - const record = { fields: request.updateData, tokens: options?.getTokens() }; + const skyflowId = request.data[SKYFLOW_ID]; + delete request.data[SKYFLOW_ID]; + const record = { fields: request.data, tokens: options?.getTokens() }; const strictMode = options?.getTokenMode() ? V1BYOT.Enable : V1BYOT.Disable; const updateData: RecordServiceUpdateRecordBody = { record: record, @@ -265,7 +267,7 @@ class VaultController { (headers: RawAxiosRequestConfig | undefined) => this.client.vaultAPI.recordServiceUpdateRecord( this.client.vaultId, request.tableName, - request.skyflowId, + skyflowId, updateData, headers ), @@ -298,7 +300,7 @@ class VaultController { validateDeleteRequest(request, this.client.getLogLevel()); const deleteRequest: RecordServiceBulkDeleteRecordBody = { - skyflow_ids: request.deleteIds, + skyflow_ids: request.ids, }; this.handleRequest( @@ -474,7 +476,7 @@ class VaultController { //validations checks validateDetokenizeRequest(request, options, this.client.getLogLevel()); - const fields = request.tokens.map(record => ({ token: record, redaction: request?.redactionType })) as Array; + const fields = request.tokens.map(record => ({ token: record, redaction: request?.redactionType || RedactionType.PLAIN_TEXT })) as Array; const detokenizePayload: V1DetokenizePayload = { detokenizationParameters: fields, continueOnError: options?.getContinueOnError(), downloadURL: options?.getDownloadURL() }; this.handleRequest( @@ -505,7 +507,7 @@ class VaultController { //validation checks validateTokenizeRequest(request, this.client.getLogLevel()); - const fields = request.values.map((record: tokenizeRequestType) => ({ value: record.value, columnGroup: record.columnGroup })) as Array; + const fields = request.values.map((record: TokenizeRequestType) => ({ value: record.value, columnGroup: record.columnGroup })) as Array; const tokenizePayload: V1TokenizePayload = { tokenizationParameters: fields }; this.handleRequest( diff --git a/src/vault/model/request/delete/index.ts b/src/vault/model/request/delete/index.ts index 647c763..aaec334 100644 --- a/src/vault/model/request/delete/index.ts +++ b/src/vault/model/request/delete/index.ts @@ -3,12 +3,12 @@ class DeleteRequest { //fields private _tableName: string; - private _deleteIds: Array; + private _ids: Array; // Constructor constructor(tableName: string, deleteIds: Array) { this._tableName = tableName; - this._deleteIds = deleteIds; + this._ids = deleteIds; } // Getter for tableName @@ -22,13 +22,13 @@ class DeleteRequest { } // Getter for deleteData - public get deleteIds(): Array { - return this._deleteIds; + public get ids(): Array { + return this._ids; } // Setter for deleteData - public set deleteIds(value: Array) { - this._deleteIds = value; + public set ids(value: Array) { + this._ids = value; } } diff --git a/src/vault/model/request/inkove/index.ts b/src/vault/model/request/inkove/index.ts index e631be7..d063bb9 100644 --- a/src/vault/model/request/inkove/index.ts +++ b/src/vault/model/request/inkove/index.ts @@ -1,16 +1,16 @@ //imports -import { Method } from "../../../../utils"; +import { RequestMethod } from "../../../../utils"; import { StringKeyValueMapType } from "../../../types"; class InvokeConnectionRequest { //fields - method: Method; + method: RequestMethod; queryParams?: StringKeyValueMapType; pathParams?: StringKeyValueMapType; body?: StringKeyValueMapType; headers?: StringKeyValueMapType; - constructor(method: Method, body?: StringKeyValueMapType, headers?: StringKeyValueMapType, pathParams?: StringKeyValueMapType, queryParams?: StringKeyValueMapType) { + constructor(method: RequestMethod, body?: StringKeyValueMapType, headers?: StringKeyValueMapType, pathParams?: StringKeyValueMapType, queryParams?: StringKeyValueMapType) { this.method = method; this.pathParams = pathParams; this.queryParams = queryParams; diff --git a/src/vault/model/request/tokenize/index.ts b/src/vault/model/request/tokenize/index.ts index a5add74..f7ef067 100644 --- a/src/vault/model/request/tokenize/index.ts +++ b/src/vault/model/request/tokenize/index.ts @@ -1,24 +1,24 @@ //imports -import { tokenizeRequestType } from "../../../types"; +import { TokenizeRequestType } from "../../../types"; class TokenizeRequest { //fields - private _values: Array; + private _values: Array; // Constructor - constructor(values: Array) { + constructor(values: Array) { this._values = values; } // Getter for _values - public get values(): Array { + public get values(): Array { return this._values; } // Setter for _values - public set values(value: Array) { + public set values(value: Array) { this._values = value; } diff --git a/src/vault/model/request/update/index.ts b/src/vault/model/request/update/index.ts index f04eaa8..3cf82cf 100644 --- a/src/vault/model/request/update/index.ts +++ b/src/vault/model/request/update/index.ts @@ -4,14 +4,12 @@ class UpdateRequest { //fields private _tableName: string; - private _skyflowId: string; - private _updateData: object; + private _data: object; // Constructor - constructor(tableName: string, skyflowId: string, updateData: object) { + constructor(tableName: string, data: object) { this._tableName = tableName; - this._skyflowId = skyflowId; - this._updateData = updateData; + this._data = data; } // Getter for tableName @@ -24,24 +22,14 @@ class UpdateRequest { this._tableName = value; } - // Getter for skyflowId - public get skyflowId(): string { - return this._skyflowId; - } - - // Setter for skyflowId - public set skyflowId(value: string) { - this._skyflowId = value; - } - // Getter for updateData - public get updateData(): object { - return this._updateData; + public get data(): object { + return this._data; } // Setter for updateData - public set updateData(value: object) { - this._updateData = value; + public set data(value: object) { + this._data = value; } } diff --git a/src/vault/model/response/invoke/invoke.ts b/src/vault/model/response/invoke/invoke.ts index cb3cf39..a09cfbf 100644 --- a/src/vault/model/response/invoke/invoke.ts +++ b/src/vault/model/response/invoke/invoke.ts @@ -4,10 +4,15 @@ import { queryResponseType } from "../../../types"; class InvokeConnectionResponse { //fields + data?: Object; + + metadata?: Object; errors?: Object; - constructor( { errors }: { errors?: object }) { + constructor({ data, metadata, errors }: { data?: object, metadata?: Object, errors?: object }) { + this.data = data; + this.metadata = metadata; this.errors = errors; } diff --git a/src/vault/types/index.ts b/src/vault/types/index.ts index 5d5561f..2efe1d8 100644 --- a/src/vault/types/index.ts +++ b/src/vault/types/index.ts @@ -38,7 +38,7 @@ export interface StringKeyValueMapType { [key: string]: object | string; } -export interface tokenizeRequestType { +export interface TokenizeRequestType { columnGroup: string; value: string; } diff --git a/test/vault/controller/connection.test.js b/test/vault/controller/connection.test.js index 5f04791..1ec65e3 100644 --- a/test/vault/controller/connection.test.js +++ b/test/vault/controller/connection.test.js @@ -1,5 +1,5 @@ import axios from "axios"; -import { fillUrlWithPathAndQueryParams, generateSDKMetrics, getBearerToken, LogLevel, MessageType, Method, parameterizedString, printLog, SDK_METRICS_HEADER_KEY, TYPES } from "../../../src/utils"; +import { fillUrlWithPathAndQueryParams, generateSDKMetrics, getBearerToken, LogLevel, MessageType, RequestMethod, parameterizedString, printLog, SDK_METRICS_HEADER_KEY, TYPES } from "../../../src/utils"; import logs from "../../../src/utils/logs"; import { validateInvokeConnectionRequest } from "../../../src/utils/validations"; import VaultClient from "../../../src/vault/client"; @@ -24,7 +24,7 @@ describe("ConnectionController", () => { pathParams: { id: "123" }, queryParams: { search: "test" }, body: { data: "sample" }, - method: Method.POST, + method: RequestMethod.POST, headers: { "Custom-Header": "value" }, }; @@ -46,7 +46,7 @@ describe("ConnectionController", () => { expect(getBearerToken).toHaveBeenCalledWith(mockClient.getCredentials(), LogLevel.ERROR); expect(axios).toHaveBeenCalledWith({ url: "https://api.example.com/resource", - method: Method.POST, + method: RequestMethod.POST, data: invokeRequest.body, headers: { ...invokeRequest.headers, @@ -62,7 +62,7 @@ describe("ConnectionController", () => { pathParams: { id: "123" }, queryParams: { search: "test" }, body: { data: "sample" }, - method: Method.POST, + method: RequestMethod.POST, headers: { "Custom-Header": "value" }, }; @@ -79,7 +79,7 @@ describe("ConnectionController", () => { pathParams: { id: "123" }, queryParams: { search: "test" }, body: { data: "sample" }, - // method: Method.POST, + // method: RequestMethod.POST, headers: { "Custom-Header": "value" }, }; @@ -114,7 +114,7 @@ describe("ConnectionController", () => { pathParams: { id: "123" }, queryParams: { search: "test" }, body: { data: "sample" }, - method: Method.POST, + method: RequestMethod.POST, headers: { "Custom-Header": "value" }, }; diff --git a/test/vault/controller/vault.test.js b/test/vault/controller/vault.test.js index 7ebc2e5..ce57af5 100644 --- a/test/vault/controller/vault.test.js +++ b/test/vault/controller/vault.test.js @@ -36,6 +36,13 @@ jest.mock('../../../src/utils', () => ({ LOG: 'LOG', ERROR: 'ERROR', }, + RedactionType: { + DEFAULT: 'DEFAULT', + PLAIN_TEXT: 'PLAIN_TEXT', + MASKED: 'MASKED', + REDACTED: 'REDACTED', + }, + SKYFLOW_ID: 'skyflowId', TYPES: { INSERT: 'INSERT', INSERT_BATCH: 'INSERT_BATCH', @@ -923,10 +930,10 @@ describe('VaultController update method', () => { }); test('should successfully update record', async () => { + const skyflowId = 'id123'; const mockRequest = { - updateData: { field1: 'value1' }, + data: { field1: 'value1', skyflowId }, tableName: 'testTable', - skyflowId: 'id123', }; const mockOptions = { getReturnTokens: jest.fn().mockReturnValue(true), @@ -942,7 +949,7 @@ describe('VaultController update method', () => { expect(mockVaultClient.vaultAPI.recordServiceUpdateRecord).toHaveBeenCalledWith( mockVaultClient.vaultId, mockRequest.tableName, - mockRequest.skyflowId, + skyflowId, expect.any(Object), // Update data expect.any(Object) // Headers ); @@ -953,10 +960,10 @@ describe('VaultController update method', () => { }); test('should successfully update record', async () => { + const skyflowId = 'id123'; const mockRequest = { - updateData: { field1: 'value1' }, + data: { field1: 'value1', skyflowId }, tableName: 'testTable', - skyflowId: 'id123', }; const mockOptions = null; const mockResponseData = {data: { skyflow_id: 'id123', tokens: { field1: 'token123' } }}; @@ -968,7 +975,7 @@ describe('VaultController update method', () => { expect(mockVaultClient.vaultAPI.recordServiceUpdateRecord).toHaveBeenCalledWith( mockVaultClient.vaultId, mockRequest.tableName, - mockRequest.skyflowId, + skyflowId, expect.any(Object), // Update data expect.any(Object) // Headers ); @@ -978,10 +985,10 @@ describe('VaultController update method', () => { expect(response.errors).toHaveLength(0); }); test('should successfully update record using enable tokens', async () => { + const skyflowId = 'id123'; const mockRequest = { - updateData: { field1: 'value1' }, + data: { field1: 'value1', skyflowId }, tableName: 'testTable', - skyflowId: 'id123', }; const mockOptions = { getReturnTokens: jest.fn().mockReturnValue(true), @@ -997,7 +1004,7 @@ describe('VaultController update method', () => { expect(mockVaultClient.vaultAPI.recordServiceUpdateRecord).toHaveBeenCalledWith( mockVaultClient.vaultId, mockRequest.tableName, - mockRequest.skyflowId, + skyflowId, expect.any(Object), // Update data expect.any(Object) // Headers ); @@ -1009,9 +1016,8 @@ describe('VaultController update method', () => { test('should handle validation errors', async () => { const mockRequest = { - updateData: { field1: 'value1' }, + data: { field1: 'value1', skyflowId: 'id123' }, tableName: 'testTable', - skyflowId: 'id123', }; const mockOptions = { getReturnTokens: jest.fn().mockReturnValue(true), @@ -1030,9 +1036,8 @@ describe('VaultController update method', () => { test('should handle API errors during record update', async () => { const mockRequest = { - updateData: { field1: 'value1' }, + data: { field1: 'value1', skyflowId: 'id123' }, tableName: 'testTable', - skyflowId: 'id123', }; const mockOptions = { getReturnTokens: jest.fn().mockReturnValue(true), @@ -1052,9 +1057,8 @@ describe('VaultController update method', () => { test('should return updated record without tokens when token mode is disabled', async () => { const mockRequest = { - updateData: { field1: 'value1' }, + data: { field1: 'value1', skyflowId: 'id123' }, tableName: 'testTable', - skyflowId: 'id123', }; const mockOptions = { getReturnTokens: jest.fn().mockReturnValue(false), @@ -1074,9 +1078,8 @@ describe('VaultController update method', () => { test('should reject and log when API returns error during update', async () => { const mockRequest = { - updateData: { field1: 'value1' }, + data: { field1: 'value1', skyflowId: 'id123' }, tableName: 'testTable', - skyflowId: 'id123', }; const mockOptions = { getReturnTokens: jest.fn().mockReturnValue(true),