Skip to content

Commit 6ceeb42

Browse files
Merge pull request #225 from terminusdb/vars_like_python
Make vars act exactly like python client
2 parents be27736 + c5f5a55 commit 6ceeb42

23 files changed

+256
-106
lines changed

.babelrc

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
{
2+
3+
"sourceType": "unambiguous",
24
"presets": ["@babel/preset-env"],
35
"plugins": ["@babel/plugin-transform-regenerator",
46
"@babel/plugin-transform-runtime"]

docs/api/accesscontrol.md

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -242,25 +242,33 @@ accessControl.deleteUser(userId).then(result=>{
242242
```
243243

244244
## manageCapability
245-
##### accessControl.manageCapability(userId, resourceId, rolesArr, operation) ⇒ <code>Promise</code>
245+
##### accessControl.manageCapability(userName, resourceName, rolesArr, operation, resourceType) ⇒ <code>Promise</code>
246246
-- TerminusdDB API ---
247247
Grant/Revoke Capability
248248

249249
**Returns**: <code>Promise</code> - A promise that returns the call response object, or an Error if rejected.
250250

251251
| Param | Type | Description |
252252
| --- | --- | --- |
253-
| userId | <code>string</code> | the document user id |
254-
| resourceId | <code>string</code> | the resource id (database or team) |
255-
| rolesArr | <code>array</code> | the roles list |
253+
| userName | <code>string</code> | the document user id |
254+
| resourceName | <code>string</code> | the name of a (database or team) |
255+
| rolesArr | <code>array</code> | the roles name list |
256256
| operation | <code>typedef.CapabilityCommand</code> | grant/revoke operation |
257+
| resourceType | <code>typedef.ResourceType</code> | the resource type (database or organization) |
257258

258259
**Example**
259260
```javascript
260-
{ "operation" : "grant",
261-
"scope" : "Organization/myteam",
262-
"user" : "User/myUser",
263-
"roles" : ["Role/reader"] }
261+
//we add an user to an organization and manage users' access
262+
//the user myUser can access the Organization and all the database under the organization with "reader" Role
263+
client.manageCapability(myUser,myteam,[reader],"grant","organization").then(result=>{
264+
consol.log(result)
265+
})
266+
267+
//the user myUser can access the database db__001 under the organization myteam
268+
//with "writer" Role
269+
client.manageCapability(myUser,myteam/db__001,[writer],"grant","database").then(result=>{
270+
consol.log(result)
271+
})
264272
```
265273

266274
## getAccessRoles

docs/api/typedef.md

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,7 @@ the DELETE document interface query parameters
9292

9393
| Name | Type | Description |
9494
| --- | --- | --- |
95-
| type | <code>&#x27;basic&#x27;</code> \| <code>&#x27;jwt&#x27;</code> | the authorization type of an TerminusDB connection |
95+
| type | <code>&#x27;basic&#x27;</code> \| <code>&#x27;jwt&#x27;</code> \| <code>&#x27;apikey&#x27;</code> | the authorization type of an TerminusDB connection |
9696
| [user] | <code>string</code> \| <code>boolean</code> | the user id | I don't need the user with the jwt token |
9797
| key | <code>string</code> | the connection key |
9898

@@ -131,6 +131,9 @@ the DELETE document interface query parameters
131131
| [invitation] | <code>string</code> | - |
132132

133133

134+
## ResourceType
135+
##### ResourceType: ` "database"` | ` "organization" `
136+
134137
## RepoType
135138
##### RepoType: ` "local"` | ` "remote" `
136139

@@ -140,13 +143,9 @@ the DELETE document interface query parameters
140143

141144
| Name | Type | Description |
142145
| --- | --- | --- |
143-
| [organization] | <code>string</code> | the db organization id |
144-
| id | <code>string</code> | The database identification name |
145146
| label | <code>string</code> | "Textual DB Name" |
146147
| [comment] | <code>string</code> | "Text description of DB" |
147148
| [public] | <code>boolean</code> | |
148-
| [icon] | <code>string</code> | The database's icon |
149-
| [prefixes] | <code>object</code> | {scm: "http://url.to.use/for/scm", doc: "http://url.to.use/for/doc"} |
150149
| [schema] | <code>boolean</code> | if set to true, a schema graph will be created |
151150

152151

docs/api/woql.md

Lines changed: 14 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -387,22 +387,6 @@ Identifies a remote resource by URL and specifies the format of the resource thr
387387
remote({url:"http://url.of.resource"}, {type: "csv"})
388388
```
389389

390-
## file
391-
##### WOQL.file(url, [formatObj]) ⇒ <code>WOQLQuery</code>
392-
Identifies a file resource as a path on the server and specifies the format through the options
393-
394-
**Returns**: <code>WOQLQuery</code> - A WOQLQuery which contains the file resource identifier
395-
396-
| Param | Type | Description |
397-
| --- | --- | --- |
398-
| url | <code>object</code> | The Path on the server at which the file resource can be accessed |
399-
| [formatObj] | <code>typedef.DataFormatObj</code> | imput options |
400-
401-
**Example**
402-
```javascript
403-
file("/path/to/file", {type: 'turtle'} )
404-
```
405-
406390
## post
407391
##### WOQL.post(url, [formatObj], [source]) ⇒ <code>WOQLQuery</code>
408392
Identifies a resource as a local path on the client, to be sent to the server through a
@@ -1429,6 +1413,20 @@ Gets/Sets woqlClient
14291413
| client | <code>WOQLClient</code> |
14301414

14311415

1416+
## Vars
1417+
##### WOQL.Vars(...varNames) ⇒
1418+
**Returns**: object
1419+
1420+
| Param | Type |
1421+
| --- | --- |
1422+
| ...varNames | <code>string</code> |
1423+
1424+
**Example**
1425+
```javascript
1426+
const v = WOQL.Vars('var01', 'var02', 'var03');
1427+
triple(v.var01, v.var02, v.var03)
1428+
```
1429+
14321430
## emerge
14331431
##### WOQL.emerge(auto_eval)
14341432
query module

docs/api/woqlclient.md

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1094,6 +1094,21 @@ get the database collections list
10941094
client.getBranches()
10951095
```
10961096
1097+
## getCommitsLog
1098+
##### woqlClient.getCommitsLog([dbId]) ⇒ <code>Promise</code>
1099+
get the database collections list
1100+
1101+
**Returns**: <code>Promise</code> - A promise that returns the call response object, or an Error if rejected.
1102+
1103+
| Param | Type | Description |
1104+
| --- | --- | --- |
1105+
| [dbId] | <code>string</code> | the database id |
1106+
1107+
**Example**
1108+
```javascript
1109+
client.getCommitsLog()
1110+
```
1111+
10971112
## getPrefixes
10981113
##### woqlClient.getPrefixes([dbId]) ⇒ <code>Promise</code>
10991114
get the database prefixes object

index.html

Lines changed: 38 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,41 @@
1-
<!DOCTYPE html>
1+
<!doctype html>
22
<html lang="en">
3-
<head>
4-
<meta charset="utf-8">
5-
<title>Woql Client</title>
6-
</head>
7-
<body>
8-
<script type="text/javascript">
9-
var dbClient= new TerminusClient.WOQLClient();
3+
<head>
4+
<meta charset="utf-8">
5+
<title>Woql Client</title>
6+
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
7+
</head>
8+
<body onload="startTerminusdb();">
9+
<div id="root" class="container">
10+
<div class="alert alert-primary" role="alert">WE ARE TESTING TerminusDB Client ......</div>
11+
<div class="alert alert-warning" role="alert" id="success-alert"></div>
12+
<div class="alert alert-warning" role="alert" id="success-alert01"></div>
13+
<div class="alert alert-success" role="alert" id="success-alert02"></div>
14+
</div>
15+
<script>
16+
async function startTerminusdb(){
17+
var dbClient= new TerminusDBClient.WOQLClient("http://127.0.0.1:6363",{user:"admin","key":"root",organization:"admin"});
18+
const db__01 = `myDB___${Date.now()}`
19+
try{
20+
await dbClient.createDatabase(db__01, {label: db__01 , comment: "add db", schema: true})
21+
const h5 = document.getElementById("success-alert");
22+
const newContent = document.createTextNode(`THE DATABASE ${db__01} HAS BEEN CREATED `);
23+
h5.appendChild(newContent)
24+
25+
await dbClient.deleteDatabase(db__01)
26+
27+
const h6 = document.getElementById("success-alert01");
28+
const newContent01 = document.createTextNode(`THE DATABASE ${db__01} HAS BEEN DELETED`);
29+
h6.appendChild(newContent01)
1030

11-
var connection=dbClient.connect("http://localhost");
12-
13-
connection.then((response)=>{
14-
console.log("I'm connect")
15-
dbClient.getSchema(getSchema,{"terminus:encoding":"terminus:turtle"}).then((response)=>
16-
console.log("getSchema RESPONSE OK")).catch((err)=>{
17-
console.log("PROMISE reject", 'GETSCHEMA');
18-
});
19-
20-
}).catch((err)=>{
21-
console.log("PROMISE reject", 'CONNECTION');
22-
});
23-
24-
var getSchema='terminus';
25-
26-
</script>
27-
28-
</body>
31+
const h7 = document.getElementById("success-alert02");
32+
const newContent02 = document.createTextNode(`CREATE/DELETE TerminusDB DATABASE TEST PASSED......`);
33+
h7.appendChild(newContent02)
34+
}catch(err){
35+
console.log(err)
36+
}
37+
}
38+
39+
</script>
40+
</body>
2941
</html>

index.js

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,14 @@
11
/* eslint-disable global-require */
2+
// const { Vars } = require('./lib/query/woqlDoc');
3+
24
module.exports = {
35
/**
4-
* @type {typeof import('./lib/woqlClient')}
5-
*/
6+
* @type {typeof import('./lib/query/woqlDoc')}
7+
*/
8+
Vars: require('./lib/query/woqlDoc'),
9+
/**
10+
* @type {typeof import('./lib/woqlClient')}
11+
*/
612
WOQLClient: require('./lib/woqlClient'),
713
/**
814
* @type {typeof import('./lib/utils')}

lib/accessControl.js

Lines changed: 23 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
/* eslint-disable max-len */
12
/* eslint-disable no-underscore-dangle */
23
const DispatchRequest = require('./dispatchRequest');
34
const ErrorMessage = require('./errorMessage');
@@ -289,20 +290,33 @@ AccessControl.prototype.deleteUser = function (userId) {
289290
/**
290291
* -- TerminusdDB API ---
291292
* Grant/Revoke Capability
292-
* @param {string} userId - the document user id
293-
* @param {string} resourceId - the resource id (database or team)
294-
* @param {array} rolesArr - the roles list
293+
* @param {string} userName - the document user id
294+
* @param {string} resourceName - the name of a (database or team)
295+
* @param {array} rolesArr - the roles name list
295296
* @param {typedef.CapabilityCommand} operation - grant/revoke operation
297+
* @param {typedef.ResourceType} resourceType - the resource type (database or organization)
296298
* @return {Promise} A promise that returns the call response object, or an Error if rejected.
297299
* @example
298-
{ "operation" : "grant",
299-
"scope" : "Organization/myteam",
300-
"user" : "User/myUser",
301-
"roles" : ["Role/reader"] }
300+
* //we add an user to an organization and manage users' access
301+
* //the user myUser can access the Organization and all the database under the organization with "reader" Role
302+
* client.manageCapability(myUser,myteam,[reader],"grant","organization").then(result=>{
303+
* consol.log(result)
304+
* })
305+
*
306+
* //the user myUser can access the database db__001 under the organization myteam
307+
* //with "writer" Role
308+
* client.manageCapability(myUser,myteam/db__001,[writer],"grant","database").then(result=>{
309+
* consol.log(result)
310+
* })
302311
*/
303-
AccessControl.prototype.manageCapability = function (userId, resourceId, rolesArr, operation) {
312+
313+
AccessControl.prototype.manageCapability = function (userName, resourceName, rolesArr, operation, resourceType) {
304314
const payload = {
305-
operation, user: userId, roles: rolesArr, scope: resourceId,
315+
operation,
316+
user: userName,
317+
roles: rolesArr,
318+
scope: resourceName,
319+
scope_type: resourceType,
306320
};
307321
return this.dispatch(`${this.baseURL}/capabilities`, CONST.POST, payload);
308322
};

lib/connectionConfig.js

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -466,6 +466,14 @@ ConnectionConfig.prototype.queryURL = function () {
466466
return this.branchBase('woql');
467467
};
468468

469+
/**
470+
* Generate URL for get back the commits logs
471+
* @returns {string}
472+
*/
473+
ConnectionConfig.prototype.log = function () {
474+
return this.dbBase('log');
475+
};
476+
469477
/**
470478
* get the url to update the organization role in the system database
471479
* don't change the end point (this is a terminus db server end point)

lib/dispatchRequest.js

Lines changed: 32 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,22 @@ function getResultWithDataVersion(response) {
2929
: '',
3030
};
3131
}
32+
/**
33+
* Create the authorization header string
34+
* @param {object} auth_obj
35+
* @returns {object} Object with the Authorization header
36+
*/
37+
38+
function formatAuthHeader(auth_obj) {
39+
if (!auth_obj) return '';
40+
const authType = { jwt: 'Bearer', basic: 'Basic', apikey: 'Token' };
41+
let auth_key = auth_obj.key;
42+
43+
if (auth_obj.type === 'basic') {
44+
auth_key = btoaImplementation(`${auth_obj.user}:${auth_obj.key}`);
45+
}
46+
return `${authType[auth_obj.type]} ${auth_key}`;
47+
}
3248

3349
/**
3450
* @file Dispatch Request
@@ -41,6 +57,7 @@ function getResultWithDataVersion(response) {
4157
* @param {object} customHeaders the unique reqID
4258
* @param {boolean} compress If true, compress the data with gzip if its size is bigger than 1024
4359
*/
60+
4461
// eslint-disable-next-line max-len
4562
function DispatchRequest(url, action, payload, local_auth, remote_auth = null, customHeaders = null, getDataVersion = false, compress = false) {
4663
/*
@@ -72,24 +89,30 @@ function DispatchRequest(url, action, payload, local_auth, remote_auth = null, c
7289
* I can call the local database using the local authorization key or
7390
* a jwt token
7491
*/
75-
if (local_auth && local_auth.type === 'basic') {
92+
/* if (local_auth && local_auth.type === 'basic') {
7693
const encoded = btoaImplementation(`${local_auth.user}:${local_auth.key}`);
7794
options.headers = { Authorization: `Basic ${encoded}` };
7895
} else if (local_auth && local_auth.type === 'jwt') {
7996
options.headers = { Authorization: `Bearer ${local_auth.key}` };
8097
} else if (local_auth && local_auth.type === 'apikey') {
8198
options.headers = { Authorization: `Token ${local_auth.key}` };
99+
} */
100+
/*
101+
* I can call the local database or a custom installation using the local authorization key or
102+
* I Can call TerminusX using the jwt token or an apiToken
103+
*/
104+
if (local_auth && typeof local_auth === 'object') {
105+
options.headers.Authorization = formatAuthHeader(local_auth);
82106
}
83107

84108
/*
85-
* pass the Authorization information of another
86-
* terminusdb server to the local terminusdb
87-
*/
88-
if (remote_auth && remote_auth.type === 'jwt') {
89-
options.headers['Authorization-Remote'] = `Bearer ${remote_auth.key}`;
90-
} else if (remote_auth && remote_auth.type === 'basic') {
91-
const rencoded = btoaImplementation(`${remote_auth.user}:${remote_auth.key}`);
92-
options.headers['Authorization-Remote'] = `Basic ${rencoded}`;
109+
* pass the Authorization information of another
110+
* terminusdb server to the local terminusdb
111+
* for authentication you can use jwt or the apiKey token in TerminusX or
112+
* the Basic autentication if is allowed in the custom server
113+
*/
114+
if (remote_auth && typeof remote_auth === 'object') {
115+
options.headers['Authorization-Remote'] = formatAuthHeader(remote_auth);
93116
}
94117

95118
if (customHeaders && typeof customHeaders === 'object') {

0 commit comments

Comments
 (0)