Skip to content

Commit aff000f

Browse files
Merge pull request #303 from hoijnet/main
Use default import with latest Axios
2 parents a349e94 + bf6aeda commit aff000f

File tree

11 files changed

+280
-161
lines changed

11 files changed

+280
-161
lines changed

integration_tests/create_database.test.ts

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ describe('Create a database, schema and insert data', () => {
3030
})
3131

3232
test('Insert Document Child Tom', async () => {
33-
const person = {"age":"10","name":"Tom","@type":"Child"}
33+
const person = {"age":"10","name":"Tom","@type":"Child" }
3434
const result = await client.addDocument(person);
3535
expect(result).toStrictEqual(["terminusdb:///data/Child/Tom" ]);
3636
})
@@ -47,6 +47,11 @@ describe('Create a database, schema and insert data', () => {
4747
expect(result).toStrictEqual(["terminusdb:///data/Parent/Tom%20Senior" ]);
4848
})
4949

50+
test('Get document history on an object', async () => {
51+
const result = await client.getDocumentHistory("Child/Tom");
52+
expect(result[0].message).toStrictEqual("add a new document");
53+
})
54+
5055
test('Query Person by name', async () => {
5156
const queryTemplate = {"name":"Tom", "@type":"Person" }
5257
const result = await client.getDocument({query:queryTemplate});
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
EmployeeId,Name,Title,Team,Manager
2+
001,Destiny Norris,Marketing Manager,Marketing,
3+
002,Darci Prosser,Creative Writer,Marketing,001
4+
003,Alanah Bloggs,Frontend Developer,IT,004
5+
004,Fabian Dalby,Web Service Manager,IT,
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
export const mock_employees_limit_1 = [
2+
{
3+
"Manager": {
4+
"@type": "xsd:string",
5+
"@value": "",
6+
},
7+
"Name": {
8+
"@type": "xsd:string",
9+
"@value": "Destiny Norris",
10+
},
11+
"Title": {
12+
"@type": "xsd:string",
13+
"@value": "Marketing Manager",
14+
},
15+
},
16+
]
Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
//@ts-check
2+
import { describe, expect, test, beforeAll } from '@jest/globals';
3+
import { WOQLClient, WOQL } from '../index.js';
4+
import { DbDetails, DocParamsGet } from '../dist/typescript/lib/typedef.js';
5+
import schemaJson from './persons_schema'
6+
import { mock_employees_limit_1 } from './data/employees_limit1';
7+
import fs from 'fs';
8+
9+
let client: WOQLClient //= new WOQLClient('http://localhost:6363');
10+
11+
beforeAll(() => {
12+
client = new WOQLClient("http://localhost:6363", { user: 'admin', organization: 'admin', key: 'root' })
13+
});
14+
15+
const db01 = 'db__test_woql';
16+
17+
describe('Create a database, schema and insert data', () => {
18+
test('Create a database', async () => {
19+
const dbObj: DbDetails = { label: db01, comment: 'add db', schema: true }
20+
const result = await client.createDatabase(db01, dbObj);
21+
//woqlClient return only the data no status
22+
expect(result["@type"]).toEqual("api:DbCreateResponse");
23+
expect(result["api:status"]).toEqual("api:success");
24+
});
25+
26+
test('Create a schema', async () => {
27+
const result = await client.addDocument(schemaJson, { graph_type: "schema", full_replace: true });
28+
expect(result).toStrictEqual(["Child", "Person", "Parent"]);
29+
})
30+
31+
test('Query with CSV upload from file', async () => {
32+
const query = WOQL.limit(1).and(
33+
WOQL.get(
34+
WOQL.as('Name', 'v:Name')
35+
.as('Manager', 'v:Manager')
36+
.as('Title', 'v:Title'),
37+
WOQL.post("./integration_tests/data/employees.csv")
38+
),
39+
);
40+
const result = await client.query(query, undefined, undefined, undefined, undefined,);
41+
expect(result?.bindings).toStrictEqual(mock_employees_limit_1);
42+
});
43+
44+
test('Query with CSV upload as resource attachment', async () => {
45+
const query = WOQL.limit(1).and(
46+
WOQL.get(
47+
WOQL.as('Name', 'v:Name')
48+
.as('Manager', 'v:Manager')
49+
.as('Title', 'v:Title'),
50+
WOQL.post("employees.csv")
51+
),
52+
);
53+
const data = fs.readFileSync('./integration_tests/data/employees.csv');
54+
const result = await client.query(query, undefined, undefined, undefined, undefined, [{
55+
filename: "employees.csv",
56+
data: data,
57+
}]);
58+
expect(result?.bindings).toStrictEqual(mock_employees_limit_1);
59+
});
60+
61+
test('Get branches from the server (only main)', async () => {
62+
const result = await client.getBranches();
63+
expect(result.main["@id"]).toStrictEqual("Branch/main");
64+
expect(Object.keys(result)).toStrictEqual(["main"]);
65+
});
66+
67+
test('Get commits log from the server', async () => {
68+
const result = await client.getCommitsLog();
69+
expect(result.length).toStrictEqual(1);
70+
expect(result[0]["@type"]).toStrictEqual("ValidCommit");
71+
});
72+
73+
test('Get prefixes from the server', async () => {
74+
const result = await client.getPrefixes();
75+
expect(result).toStrictEqual({"@base": "terminusdb:///data/", "@schema": "terminusdb:///schema#", "@type": "Context"});
76+
});
77+
78+
test('Get userOrganisations from the server', async () => {
79+
const result = (await client.getUserOrganizations()).filter(org => org["@id"] === "Organization/admin");
80+
expect(result[0]["@id"]).toStrictEqual("Organization/admin");
81+
});
82+
83+
test('Delete a database', async () => {
84+
const result = await client.deleteDatabase(db01);
85+
expect(result).toStrictEqual({ '@type': 'api:DbDeleteResponse', 'api:status': 'api:success' });
86+
});
87+
});

lib/axiosInstance.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
const axios = require('axios');
1+
const axios = require('axios').default;
22

3-
const axiosInstance = axios.create();
3+
const axiosInstance = axios.create({});
44

55
module.exports = axiosInstance;

lib/dispatchRequest.js

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -215,7 +215,9 @@ function DispatchRequest(url, action, payload, local_auth, remote_auth = null, c
215215
}
216216
default: {
217217
options.headers = options.headers ? options.headers : {};
218-
options.headers['Content-Type'] = 'application/json; charset=utf-8';
218+
if (!options.headers['content-type'] && !options.headers['Content-Type']) {
219+
options.headers['Content-Type'] = 'application/json; charset=utf-8';
220+
}
219221
const compressedContentPost = checkPayload(payload, options, compress);
220222
return axiosInstance
221223
.post(url, compressedContentPost || payload || {}, options)

lib/typedef.js

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -184,4 +184,10 @@ const { ACTIONS } = Utils.ACTIONS;
184184
* @property {number} [start] - Amount of commits to show, 10 is the default
185185
*/
186186

187+
/**
188+
* @typedef {Object} NamedResourceData - { filename: "data.csv", data: "col1;col2\nval1;val2" }
189+
* @property {string} filename - Filename referenced in the WOQL query
190+
* @property {string|Blob} data - Attached data, such as CSV contents
191+
*/
192+
187193
module.exports = {};

lib/woqlClient.js

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -635,14 +635,19 @@ function getResourceObjects(queryObject, result_array) {
635635
* @param {string} [lastDataVersion] the last data version tracking id.
636636
* @param {boolean} [getDataVersion] If true the function will return object having result
637637
* and dataVersion.
638+
* @param {Array<NamedResourceData>} [resources] csv resources supplied as strings
638639
* @returns {Promise} A promise that returns the call response object or object having *result*
639640
* and *dataVersion* object if ***getDataVersion*** parameter is true, or an Error if rejected.
640641
* @example
641642
* const result = await client.query(WOQL.star())
642643
*/
643-
WOQLClient.prototype.query = function (woql, commitMsg, allWitnesses, lastDataVersion = '', getDataVersion = false) {
644+
WOQLClient.prototype.query = function (woql, commitMsg, allWitnesses, lastDataVersion = '', getDataVersion = false, resources = []) {
644645
allWitnesses = allWitnesses || false;
645646
commitMsg = commitMsg || 'Commit generated with javascript client without message';
647+
648+
const providedResourcesLookupMap = (resources ?? [])
649+
.reduce((map, res) => ({ ...map, [(res.filename).split('/').pop()]: res.data }), {});
650+
646651
if (woql && woql.json && (!woql.containsUpdate() || commitMsg)) {
647652
const doql = woql.containsUpdate() ? this.generateCommitInfo(commitMsg) : {};
648653
doql.query = woql.json();
@@ -655,9 +660,17 @@ WOQLClient.prototype.query = function (woql, commitMsg, allWitnesses, lastDataVe
655660
const formData = new FormData();
656661

657662
resourceObjects.forEach((resourceObject) => {
663+
const providedResourceInsteadOfFile = typeof resourceObject.source.post === 'string'
664+
? providedResourcesLookupMap?.[resourceObject.source.post.split('/').pop()]
665+
: undefined;
666+
658667
const fileName = resourceObject.source.post.split('/').pop();
659668

660-
formData.append('file', fs.createReadStream(resourceObject.source.post));
669+
if (providedResourceInsteadOfFile) {
670+
formData.append('file', providedResourceInsteadOfFile, { filename: fileName, contentType: 'application/csv' });
671+
} else {
672+
formData.append('file', fs.createReadStream(resourceObject.source.post));
673+
}
661674
resourceObject.source.post = fileName;
662675
});
663676

0 commit comments

Comments
 (0)