-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgetUserDocumentsFromDB.ts
47 lines (40 loc) · 1.34 KB
/
getUserDocumentsFromDB.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import * as pg from "pg";
import * as _ from "lodash";
import * as request from "request-promise-native";
import OpaCompileResponseParser from "opa-compile-response-parser";
import SimpleOpaSQLTranslator from "./SimpleOpaSQLTranslator";
import createUserSessionData from "./createUserSessionData";
interface Document {
name: string;
owerName: string;
classificationLevel: number;
}
export default async function getUserDocuments(
pool: pg.Pool,
userName: string
): Promise<Document[]> {
const userData = await createUserSessionData(pool, userName);
const res = await request(`http://localhost:8181/v1/compile`, {
method: "post",
json: {
query: "data.object.document.allow == true",
input: {
user: userData
},
unknowns: ["input.document"]
}
});
const parser = new OpaCompileResponseParser();
parser.parse(res);
const sqlValues: any[] = [];
const translator = new SimpleOpaSQLTranslator(["input.document"]);
const sqlClause = translator.parse(parser.evaluate(), sqlValues);
const result = await pool.query(
`SELECT * FROM documents ${sqlClause ? `WHERE ${sqlClause}` : ""}`,
sqlValues
);
if (!result || !_.isArray(result.rows) || !result.rows.length) {
return [];
}
return result.rows;
}