Skip to content

Commit 8f50b82

Browse files
Merge pull request #5 from terminusdb/review-change-request
Review change request
2 parents a98c327 + ef0549c commit 8f50b82

File tree

12 files changed

+749
-797
lines changed

12 files changed

+749
-797
lines changed

package-lock.json

Lines changed: 680 additions & 686 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
"license": "ISC",
2020
"dependencies": {
2121
"@apollo/client": "^3.7.16",
22-
"@terminusdb/terminusdb-client": "^10.0.30",
22+
"@terminusdb/terminusdb-client": "^10.0.31",
2323
"@types/swagger-ui-express": "^4.1.3",
2424
"apollo-cache-inmemory": "^1.6.6",
2525
"apollo-client": "^2.6.10",

src/api/addContextMiddle.ts

Lines changed: 18 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,31 @@
11
import { NextFunction, Request, Response } from "express"
2-
3-
4-
const logger = {
5-
error : function (message:string){
2+
import {Logger} from './core/typeDef'
3+
// I have to add a logger strategy
4+
const logger:Logger = {
5+
error : function (...message:string[]){
66
const dd = new Date()
7-
console.log('ERROR', dd.toISOString(), message)
7+
const messageStr = Array.isArray(message) ? message.join(" ") : ''
8+
console.log('ERROR', dd.toISOString(), messageStr)
89
},
9-
debug : function (message:string){
10+
debug : function (...message:string[]){
1011
const dd = new Date()
11-
console.log('DEBUG', dd.toISOString(), message)
12+
const messageStr = Array.isArray(message) ? message.join(" ") : ''
13+
console.log('DEBUG', dd.toISOString(), messageStr)
1214
},
13-
info : function (message:string){
15+
info : function (...message:string[]){
1416
const dd = new Date()
15-
console.log('INFO', dd.toISOString(), message)
17+
const messageStr = Array.isArray(message) ? message.join(" ") : ''
18+
console.log('INFO', dd.toISOString(), messageStr)
1619
},
17-
warning : function (message:string){
20+
warn : function (...message:string[]){
1821
const dd = new Date()
19-
console.log('WARNING', dd.toISOString(), message)
22+
const messageStr = Array.isArray(message) ? message.join(" ") : ''
23+
console.log('WARNING', dd.toISOString(), messageStr)
2024
}
2125
}
2226

2327
export const addContextMiddle = function (req:Request, res:Response, next:NextFunction) {
24-
var dd = new Date()
25-
console.log("addContextMiddle",dd.toISOString())
28+
var dd = new Date()
2629
if(req.url.startsWith("/api-docs")){
2730
return next();
2831
}
@@ -34,10 +37,10 @@ export const addContextMiddle = function (req:Request, res:Response, next:NextFu
3437
const base64Url = auth.split('Basic')[1]
3538
const basicDecode = atob(base64Url)
3639
const basicArr = basicDecode.split(':')
37-
req.context = {user : basicArr[0], password : basicArr[1]}//, logger }
40+
req.context = {user : basicArr[0], password : basicArr[1],logger:logger}
3841
//to be review
3942
}catch(err:any){
40-
console.log(err.message)
43+
logger.error("addContextMiddle", err.message)
4144
return res.status(401).send("Unauthorized")
4245
}
4346
next()

src/api/core/ChangeRequestDB.ts

Lines changed: 15 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -4,69 +4,50 @@ import { Request } from "express"
44
import * as typeDef from "./typeDef"
55
import {ApiError} from "./ApiError"
66
import * as IndexClient from './IndexClient'
7+
import * as settings from './settings'
78

89
import dbSchema from '../../change_request_schema.json'
910
import { doc } from "@terminusdb/terminusdb-client/dist/typescript/lib/woql"
1011
//import {v4 as uuidv4} from 'uuid';
1112
const { v4: uuidv4 } = require('uuid');
1213

13-
const endpoint :string = process.env.SERVER_ENDPOINT || "http://127.0.0.1:6363"
14-
const key = process.env.USER_KEY || "root"
15-
const CROrg = process.env.CR_TEAM_NAME || "terminusCR"
16-
const user = process.env.USER_NAME || "admin"
17-
18-
19-
const logger = {
20-
error : function (message:string){
21-
const dd = new Date()
22-
console.log('ERROR', dd.toISOString(), message)
23-
},
24-
debug : function (message:string){
25-
const dd = new Date()
26-
console.log('DEBUG', dd.toISOString(), message)
27-
},
28-
info : function (message:string){
29-
const dd = new Date()
30-
console.log('INFO', dd.toISOString(), message)
31-
},
32-
warning : function (message:string){
33-
const dd = new Date()
34-
console.log('WARNING', dd.toISOString(), message)
35-
}
36-
}
14+
//const endpoint :string = process.env.SERVER_ENDPOINT || "http://127.0.0.1:6363"
15+
//const key = process.env.USER_KEY || "root"
16+
//const CROrg = process.env.CR_TEAM_NAME || "terminusCR"
17+
//const user = process.env.USER_NAME || "admin"
3718
class ChangeRequestDB {
3819
client: WOQLClient;
39-
accessControl: AccessControl;
4020
request : Request
4121
user : string | undefined
4222
password : string | undefined
4323
orgName : string | undefined
4424
dbName : string | undefined
4525
changeRequestDbName: string | undefined
46-
logger : Object
26+
logger : typeDef.Logger
4727
endStatus:any = { Assigned: true, Error: true }
4828
availableStatus:any = { Assigned: true, Error: true, Progress: true }
29+
errorMessage:any = {'api:UnknownDatabase':true,'api:NoUniqueIdForOrganizationName':true}
4930

5031
constructor(req : Request) {
5132
this.request = req
5233
this.password = req.context.password
5334
this.user = req.context.user
5435
// user that has admin privileges for the terminuscms team
55-
this.client = new TerminusClient.WOQLClient(endpoint, { key: key, user: user })
56-
this.client.organization(CROrg)
36+
this.client = new TerminusClient.WOQLClient(settings.endpoint, { key:settings.key, user: settings.user })
37+
this.client.organization(settings.CROrg)
5738
this.orgName = req.params.org
5839
this.dbName = req.params.db
59-
this.logger = logger//req.context.logger
40+
this.logger = req.context.logger
6041
// every dataproduct has the related change_request database
6142
this.changeRequestDbName = `${TerminusClient.UTILS.encodeURISegment(this.orgName)}__${this.dbName}__CR`
62-
this.accessControl = new AccessControl(endpoint, { key: key, user: user })
6343
this.client.db(this.changeRequestDbName)
6444
}
6545

6646
// check if the user is authorized to see this change request db
6747
// maybe I can add a capability at database level
6848
// admin create the db
6949
// and add the capability
50+
7051
async getChangeRequests (changeId: String | false = false, as_list = true) {
7152
const params : DocParamsGet = { type: 'ChangeRequest', as_list: as_list}
7253
if (changeId) {
@@ -77,21 +58,14 @@ class ChangeRequestDB {
7758
return result
7859
} catch (err:any) {
7960
// if there is no change request we return an empty array
80-
if (typeof err.data === 'object' && err.data['api:error'] && err.data['api:error']['@type'] === 'api:UnknownDatabase') {
61+
if (typeof err.data === 'object' && err.data['api:error']
62+
&& this.errorMessage[err.data['api:error']['@type']]) {
8163
return []
8264
}
8365
throw err
8466
}
8567
}
8668

87-
async createTeam(){
88-
try{
89-
await this.accessControl.createOrganization(CROrg)
90-
}catch(err){
91-
// the team already exists
92-
}
93-
}
94-
9569
async createCRDatabase(){
9670
try {
9771
if(this.changeRequestDbName){
@@ -106,7 +80,7 @@ class ChangeRequestDB {
10680
} catch (err:any) {
10781

10882
// the database already exists
109-
//this.logger.debug(`the change request db already exists ${err.message}`)
83+
this.logger.debug(`the change request db already exists ${err.message}`)
11084
}
11185
}
11286

@@ -162,7 +136,7 @@ class ChangeRequestDB {
162136

163137
// I'm using the current user to connect with the database that is going to be modified
164138
connectWithCurrentUser () {
165-
const tmpClient = new TerminusClient.WOQLClient(endpoint, { user: this.user, organization: this.orgName })
139+
const tmpClient = new TerminusClient.WOQLClient(settings.endpoint, { user: this.user, organization: this.orgName })
166140
// I remove the basic authentication type header
167141
tmpClient.localAuth({ user: this.user, type: "basic", key: this.password || '' })
168142
tmpClient.db(this.dbName)

src/api/core/GraphqlTableConfig.ts

Lines changed: 5 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
import { ApolloClient, InMemoryCache, gql, concat,HttpLink,ApolloLink } from '@apollo/client/core';
33
import { Request } from "express"
44
import TerminusClient from '@terminusdb/terminusdb-client'
5-
import { AdvancedSearchField } from './typeDef'
5+
import { AdvancedSearchField,Logger } from './typeDef'
66
const endpoint = process.env.SERVER_ENDPOINT || ""
77
const key = process.env.USER_KEY || ""
88
const user = process.env.USER_NAME || ""
@@ -137,25 +137,6 @@ const advancedSearchMatchType : Record<AdvancedKeyType,AdvancedSearchField> = {
137137
}
138138
}
139139

140-
const logger = {
141-
error : function (message:string){
142-
const dd = new Date()
143-
console.log('ERROR', dd.toISOString(), message)
144-
},
145-
debug : function (message:string){
146-
const dd = new Date()
147-
console.log('DEBUG', dd.toISOString(), message)
148-
},
149-
info : function (message:string){
150-
const dd = new Date()
151-
console.log('INFO', dd.toISOString(), message)
152-
},
153-
warning : function (message:string){
154-
const dd = new Date()
155-
console.log('WARNING', dd.toISOString(), message)
156-
}
157-
}
158-
159140
const query = gql(`{__schema
160141
{ types{...FullType}
161142
directives{name description locations args{...InputValue}}}}
@@ -173,7 +154,7 @@ class GraphqlTableConfig {
173154
password : string | undefined
174155
orgName : string | undefined
175156
dbName : string | undefined
176-
logger : typeof logger
157+
logger : Logger
177158

178159
constructor(req : Request) {
179160
this.request = req
@@ -182,7 +163,7 @@ class GraphqlTableConfig {
182163
// user that has admin privileges for the terminuscms team
183164
this.orgName = req.params.org
184165
this.dbName = req.params.db
185-
this.logger = logger//req.context.logger
166+
this.logger = req.context.logger
186167
// every dataproduct has the related change_request database
187168
}
188169

@@ -219,7 +200,6 @@ class GraphqlTableConfig {
219200
const result = await client.query({ query })
220201
const schemaDoc = await woqlClient.getDocument({ graph_type: 'schema', as_list: true })
221202
const tableConfig = this.formatSchema(result, schemaDoc)
222-
//this.logger.debug(JSON.stringify(tableConfig, null, 4))
223203
return tableConfig
224204
}
225205

@@ -243,10 +223,6 @@ class GraphqlTableConfig {
243223

244224
advSearchFilterFormatter (typesObj:any, fieldKey:string, fieldTypeValue:AdvancedKeyType, isList:boolean) {
245225
try{
246-
if(fieldKey==="homeworld"){
247-
console.log("stop")
248-
249-
}
250226
let advField:AdvancedSearchField = advancedSearchMatchType[fieldTypeValue] || {}
251227
if (advField !== undefined) {
252228
advField = JSON.parse(JSON.stringify(advField))
@@ -260,7 +236,7 @@ class GraphqlTableConfig {
260236
advField.typevalue = fieldTypeValue
261237
return advField
262238
}catch(err:any){
263-
console.log("advSearchFilterFormatter",fieldKey,fieldTypeValue)
239+
this.logger.error("advSearchFilterFormatter",fieldKey,fieldTypeValue)
264240
throw err
265241
}
266242
}
@@ -282,7 +258,6 @@ class GraphqlTableConfig {
282258

283259
formatSchema(result:any, schemaDoc:any) {
284260
const types: GraphQLSchemaType[] = result.data.__schema.types
285-
//console.log(types)
286261
const typesObj01:any = types[0]
287262
const name = typesObj01.name
288263
const typesObj:ObjectMap = {}
@@ -291,7 +266,6 @@ class GraphqlTableConfig {
291266
const itemMatch = schemaDoc.find((doc:any) => doc['@id'] === name ||
292267
`${doc['@id']}_Filter` === name || `${doc['@id']}_Ordering` === name)
293268
if (itemMatch) {
294-
console.log("TYPE NAME",name , kind)
295269
const ordering = itemMatch['@metadata'] && itemMatch['@metadata'].order_by ? { order_by: itemMatch['@metadata'].order_by } : {}
296270
typesObj[name] = { type: kind, ...ordering }
297271
// to be review
@@ -481,7 +455,7 @@ class GraphqlTableConfig {
481455
objQuery[key] = {
482456
query: `
483457
query ${key}Query($offset: Int, $limit: Int ${filter} ${order} ){
484-
${key}(offset: $offset, limit: $limit ${filterVar} ${orderVar}){
458+
${key}(include_children:false, offset: $offset, limit: $limit ${filterVar} ${orderVar}){
485459
_id
486460
${fieldKeysArr.join(' \n ')}
487461
}

src/api/core/Person.ts

Lines changed: 0 additions & 14 deletions
This file was deleted.

src/api/core/index.ts

Lines changed: 0 additions & 2 deletions
This file was deleted.

src/api/core/settings.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
export const endpoint :string = process.env.SERVER_ENDPOINT || "http://127.0.0.1:6363"
2+
export const key = process.env.USER_KEY || "root"
3+
export const CROrg = process.env.CR_TEAM_NAME || "terminusCR"
4+
export const user = process.env.USER_NAME || "admin"
5+

src/api/core/typeDef.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11

22
export type ChangeReqStatus = "Submitted" | "Open" | "Rejected" | "Merged"
3+
export type Logger = {error:Function, debug:Function, info:Function, warn:Function}
34
export type MessageObj = {"@type" : "Message",
45
"text":string,
56
"timestamp":number,

src/api/custom.d.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
declare namespace Express {
22
export interface Request {
3-
context: {user:string ,password:string}
3+
context: {user:string ,password:string,logger:any}
44
}
55
}

src/api/paths/api/changes/{org}/{db}/index.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,12 @@ import ChangeRequestDB from "../../../../../core/ChangeRequestDB";
66

77
export const GET: Operation = async(req:Request, res:Response) =>{
88
try{
9-
var dd = new Date()
10-
console.log("ChangeRequestDB",dd.toISOString())
9+
//var dd = new Date()
10+
//console.log("ChangeRequestDB",dd.toISOString())
1111
const changeR = new ChangeRequestDB(req)
1212
const result = await changeR.getChangeRequests()
13-
var dd1 = new Date()
14-
console.log("ChangeRequestDB",dd1.toISOString())
13+
//var dd1 = new Date()
14+
//console.log("ChangeRequestDB",dd1.toISOString())
1515
res.status(200).json(result);
1616
}catch(err:any){
1717
console.log(err.message)

src/app.ts

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ import bodyParser from "body-parser";
1111
import cors from "cors";
1212
import {addContextMiddle} from "./api/addContextMiddle"
1313
import { createProxyMiddleware } from 'http-proxy-middleware'
14-
14+
import TerminusClient , {WOQLClient,WOQL, AccessControl} from "@terminusdb/terminusdb-client"
1515
declare namespace Express {
1616
export interface Request {
1717
context?: object
@@ -66,7 +66,24 @@ app.use(
6666
);
6767

6868
app.use(addContextMiddle)
69-
app.listen(3035);
69+
app.listen(3035,function(){
70+
// when we start the server we check if the terminusCR team already exists
71+
// if it does not exists we'll create it
72+
const endpoint :string = process.env.SERVER_ENDPOINT || "http://127.0.0.1:6363"
73+
const key = process.env.USER_KEY || "root"
74+
const CROrg = process.env.CR_TEAM_NAME || "terminusCR"
75+
const user = process.env.USER_NAME || "admin"
76+
const accessControl = new AccessControl(endpoint, { key: key, user: user })
77+
78+
accessControl.createOrganization(CROrg).then(result=>{
79+
console.log("The Change Request team has been created")
80+
}).catch((err:any)=>{
81+
if (typeof err.data === 'object' && err.data['api:error']
82+
&& err.data['api:error']['@type'] === "api:NoUniqueIdForOrganizationName") {
83+
console.log("The Change Request team already exists")
84+
}
85+
})
86+
});
7087

7188
console.log("App running on port http://localhost:3035");
7289
console.log(

0 commit comments

Comments
 (0)