@quillsql/node 0.2.6 → 0.2.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,55 @@
1
+ # Quill Node SDK
2
+
3
+ ## Installation
4
+
5
+ ```shell
6
+ $ npm install @quillsql/node
7
+
8
+ # Or, if you prefer yarn
9
+ $ yarn add @quillsql/node
10
+ ```
11
+
12
+ ## Usage
13
+
14
+ Instantiate quill with your credentials and add the below POST endpoint.
15
+
16
+ Note that we assume you have an organization id on the user returned by your auth middleware. Queries will not work properly without the organization id.
17
+
18
+ ```js
19
+ const quill = require("@quillsql/node")({
20
+ privateKey: process.env.QULL_PRIVATE_KEY,
21
+ databaseConnectionString: process.env.POSTGRES_READ,
22
+ });
23
+
24
+ // "authenticateJWT" is your own pre-existing auth middleware
25
+ app.post("/quill", authenticateJWT, async (req, res) => {
26
+ // assuming user fetched via auth middleware has an organizationId
27
+ const { organizationId } = req.user;
28
+ const { metadata } = req.body;
29
+ const result = await quill.query({
30
+ orgId: organizationId,
31
+ metadata,
32
+ });
33
+ res.send(result);
34
+ });
35
+ ```
36
+
37
+ ## For local testing (dev purposes only)
38
+
39
+ Create an .env file with the following key-value pairs:
40
+
41
+ ```
42
+ QUILL_PRIVATE_KEY=
43
+ DB_URL=
44
+ ENV=development
45
+ BACKEND_URL=
46
+ ```
47
+
48
+ Use the following commands to start a locally hosted dev server.
49
+
50
+ ```
51
+ npm install
52
+ npm run dev-server
53
+ ```
54
+
55
+ You should be able to ping your local server at `http://localhost:3000`.
@@ -0,0 +1,35 @@
1
+ // Write a simple node server to test the SDK
2
+
3
+ import express from "express";
4
+ import Quill from "../../src/index";
5
+ import cors from "cors";
6
+
7
+ const app = express();
8
+ const port = 3000;
9
+
10
+ const quill = new Quill(
11
+ process.env.QUILL_PRIVATE_KEY as string,
12
+ process.env.DB_URL as string,
13
+ {}
14
+ );
15
+
16
+ app.use(cors());
17
+ app.use(express.json());
18
+
19
+ app.get("/", (req, res) => {
20
+ res.send("Hello World!");
21
+ });
22
+
23
+ app.post("/quill", async (req, res) => {
24
+ const organizationId = req.body.orgId;
25
+ const { metadata } = req.body;
26
+ const result = await quill.query({
27
+ orgId: organizationId,
28
+ metadata,
29
+ });
30
+ res.send(result);
31
+ });
32
+
33
+ app.listen(port, () => {
34
+ console.log(`Example app listening at http://localhost:${port}`);
35
+ });
package/jest.config.js ADDED
@@ -0,0 +1,19 @@
1
+ module.exports = {
2
+ "browser": false,
3
+ "automock": false,
4
+ "testEnvironment": "node",
5
+ "collectCoverage": false,
6
+ "transform": {
7
+ ".(ts|tsx)": "ts-jest"
8
+ },
9
+ "transformIgnorePatterns": ['^.+\\.(js|json)$'],
10
+ "testRegex": "(/__tests__/.*|src.*?\\.(ispec|uspec))\\.(ts)$",
11
+ "testPathIgnorePatterns": [
12
+ "//node_modules/"
13
+ ],
14
+ "moduleFileExtensions": [
15
+ "ts",
16
+ "js",
17
+ "json"
18
+ ]
19
+ };
package/package.json CHANGED
@@ -1,23 +1,34 @@
1
1
  {
2
2
  "name": "@quillsql/node",
3
- "version": "0.2.6",
4
- "description": "Quill SDK for Node.js",
5
- "main": "dist/index.js",
3
+ "version": "0.2.8",
4
+ "description": "Quill's client SDK for node backends.",
5
+ "main": "dist/index.ts",
6
6
  "scripts": {
7
- "build": "tsc",
8
- "test": "echo \"Error: no test specified\" && exit 1"
7
+ "build": "tsc --outDir dist",
8
+ "start:dev": "nodemon ./examples/node-server/app.ts",
9
+ "integration-tests": "jest '.*\\.ispec\\.ts$'",
10
+ "test": "tsc src && jest --detectOpenHandles"
11
+ },
12
+ "author": "lagambino",
13
+ "license": "ISC",
14
+ "devDependencies": {
15
+ "@types/cors": "^2.8.17",
16
+ "@types/express": "^4.17.21",
17
+ "@types/jest": "^29.5.11",
18
+ "@types/node": "^20.10.7",
19
+ "@types/pg": "^8.10.9",
20
+ "cors": "^2.8.5",
21
+ "express": "^4.18.2",
22
+ "jest": "^29.7.0",
23
+ "nodemon": "^3.0.2",
24
+ "ts-node": "^10.9.2",
25
+ "typescript": "^5.3.3"
9
26
  },
10
- "author": "Quill",
11
- "license": "MIT",
12
27
  "dependencies": {
13
- "axios": "^0.21.4",
28
+ "axios": "^1.6.5",
14
29
  "dotenv": "^16.3.1",
15
- "pg": "^8.11.1",
16
- "pg-error": "^1.1.0"
17
- },
18
- "devDependencies": {
19
- "@types/node": "^20.4.2",
20
- "ts-node": "^10.9.1",
21
- "typescript": "^5.1.6"
30
+ "pg": "^8.11.3",
31
+ "redis": "^4.6.12",
32
+ "ts-jest": "^29.1.1"
22
33
  }
23
34
  }
@@ -0,0 +1,23 @@
1
+ import axios from "axios";
2
+
3
+ /** This client is currently not used but is a good design pratice */
4
+
5
+ class QuillServerClient {
6
+ private baseUrl: string;
7
+ private config: {
8
+ headers: {
9
+ Authorization: string;
10
+ };
11
+ };
12
+
13
+ constructor(privateKey: string) {
14
+ this.baseUrl = "";
15
+ this.config = { headers: { Authorization: `Bearer ${privateKey}` } };
16
+ }
17
+
18
+ public async postQuill(route: string, payload: any): Promise<any> {
19
+ return axios.post(`${this.baseUrl}/${route}`, payload, this.config);
20
+ }
21
+ }
22
+
23
+ export default QuillServerClient;
@@ -0,0 +1,97 @@
1
+ import { Pool } from "pg";
2
+ import { Mapable, CacheCredentials } from "../models/Cache";
3
+ import { QuillConfig } from "../models/Quill";
4
+ import { createClient } from "redis";
5
+ import { isSuperset } from "../utils/Error";
6
+
7
+ class PgError extends Error {
8
+ code?: string;
9
+ detail?: string;
10
+ hint?: string;
11
+ position?: string;
12
+ // Add other properties if needed
13
+ constructor(detail?: string, hint?: string, position?: string) {
14
+ super();
15
+ this.detail = detail;
16
+ this.hint = hint;
17
+ this.position = position;
18
+ }
19
+ }
20
+
21
+ /** The TTL for new cache entries (default: 1h) */
22
+ const DEFAULT_CACHE_TTL = 24 * 60 * 60;
23
+
24
+ export class CachedPool {
25
+ public pool: Pool;
26
+ public orgId: any;
27
+ public ttl: number;
28
+ public cache: Mapable | null;
29
+
30
+ constructor(config: any, cacheConfig: Partial<CacheCredentials> = {}) {
31
+ this.pool = new Pool(config);
32
+ this.ttl = cacheConfig?.ttl ?? DEFAULT_CACHE_TTL;
33
+ this.cache = this.getCache(cacheConfig);
34
+ }
35
+
36
+ public async query(text: string, values?: any[]): Promise<any> {
37
+ try {
38
+ if (!this.cache) {
39
+ const results = await this.pool.query(text, values);
40
+ return {
41
+ fields: results.fields.map((field: any) => ({
42
+ name: field.name,
43
+ dataTypeID: field.dataTypeID,
44
+ })),
45
+ rows: results.rows,
46
+ };
47
+ }
48
+ const key: string = `${this.orgId}:${text}`;
49
+ const cachedResult: string | null = await this.cache.get(key);
50
+ if (cachedResult) {
51
+ return JSON.parse(cachedResult);
52
+ } else {
53
+ const newResult: any = await this.pool.query(text, values);
54
+ const newResultString: string = JSON.stringify(newResult);
55
+ await this.cache.set(key, newResultString, "EX", DEFAULT_CACHE_TTL);
56
+ return {
57
+ fields: newResult.fields.map((field: any) => ({
58
+ name: field.name,
59
+ dataTypeID: field.dataTypeID,
60
+ })),
61
+ rows: newResult.rows,
62
+ };
63
+ }
64
+ } catch (err) {
65
+ if (isSuperset(err, PgError)) {
66
+ throw new PgError(
67
+ (err as any).detail,
68
+ (err as any).hint,
69
+ (err as any).position
70
+ );
71
+ } else if (err instanceof Error) {
72
+ throw new Error(err.message);
73
+ }
74
+ }
75
+ }
76
+
77
+ /**
78
+ * Configures and returns a cache instance or null if none could be created.
79
+ */
80
+ private getCache({
81
+ username,
82
+ password,
83
+ host,
84
+ port,
85
+ cacheType,
86
+ }: QuillConfig["cache"]): Mapable | null {
87
+ if (cacheType === "redis" || cacheType === "rediss") {
88
+ const redisURL = `${cacheType}://${username}:${password}@${host}:${port}`;
89
+ return createClient({ url: redisURL }) as Mapable;
90
+ }
91
+ return null;
92
+ }
93
+
94
+ async close() {
95
+ await this.pool.end();
96
+ }
97
+ }
@@ -0,0 +1,36 @@
1
+ import Quill from ".";
2
+ import "dotenv/config";
3
+
4
+ const HOST =
5
+ process.env.ENV === "development"
6
+ ? "http://localhost:8080"
7
+ : "https://quill-344421.uc.r.appspot.com";
8
+
9
+ describe("Quill", () => {
10
+ let quill: Quill;
11
+
12
+ beforeEach(() => {
13
+ quill = new Quill(
14
+ process.env.QUILL_PRIVATE_KEY as string,
15
+ process.env.DB_URL as string
16
+ );
17
+ });
18
+
19
+ afterAll(() => {
20
+ jest.restoreAllMocks();
21
+ });
22
+
23
+ describe("query", () => {
24
+ it("org - should return ", async () => {
25
+ const metadata = {
26
+ task: "orgs",
27
+ clientId: "62cda15d7c9fcca7bc0a3689",
28
+ };
29
+ const result = await quill.query({
30
+ orgId: "2",
31
+ metadata,
32
+ });
33
+ // TODO - add assertions
34
+ });
35
+ });
36
+ });
package/src/index.ts ADDED
@@ -0,0 +1,144 @@
1
+ import QuillServerClient from "./clients/QuillServerClient";
2
+ import { CacheCredentials } from "./models/Cache";
3
+ import {
4
+ AdditionalProcessing,
5
+ QuillClientResponse,
6
+ QuillQueryParams,
7
+ } from "./models/Quill";
8
+ import { CachedPool } from "./db/CachedPools";
9
+ import axios from "axios";
10
+ import "dotenv/config";
11
+ import {
12
+ getTableSchema,
13
+ mapQueries,
14
+ removeFields,
15
+ } from "./utils/RunQueryProcesses";
16
+
17
+ const HOST =
18
+ process.env.ENV === "development"
19
+ ? "http://localhost:8080"
20
+ : "https://quill-344421.uc.r.appspot.com";
21
+
22
+ /**
23
+ * Quill - Fullstack API Platform for Dashboards and Reporting.
24
+ */
25
+ export default class Quill {
26
+ // Configure cached connection pools with the given config.
27
+ private connectionString;
28
+ private ssl = { rejectUnauthorized: false };
29
+ public targetPool;
30
+ private baseUrl: string;
31
+ private config: {
32
+ headers: {
33
+ Authorization: string;
34
+ };
35
+ };
36
+
37
+ constructor(
38
+ privateKey: string,
39
+ databaseConnectionString: string,
40
+ cache: Partial<CacheCredentials> = {}
41
+ ) {
42
+ this.baseUrl = HOST;
43
+ this.config = { headers: { Authorization: `Bearer ${privateKey}` } };
44
+ this.connectionString = databaseConnectionString;
45
+ this.ssl = { rejectUnauthorized: false };
46
+ this.targetPool = new CachedPool(
47
+ { connectionString: this.connectionString, ssl: this.ssl },
48
+ cache
49
+ );
50
+ }
51
+
52
+ public async query({ orgId, metadata }: QuillQueryParams): Promise<any> {
53
+ this.targetPool.orgId = orgId;
54
+
55
+ try {
56
+ // Initial Query Request
57
+ const preQueryResults = await this.runQueries(metadata.preQueries);
58
+ const response = await this.postQuill(metadata.task, {
59
+ ...metadata,
60
+ orgId,
61
+ preQueryResults,
62
+ });
63
+ const results = await this.runQueries(
64
+ response.queries,
65
+ response.runQueryConfig
66
+ );
67
+ // if there is no metadata object in the response, create one
68
+ if (!response.metadata) {
69
+ response.metadata = {};
70
+ }
71
+ // if there is a single query array in queryResults and the rows and field objects to metadata
72
+ if (results?.queryResults.length === 1) {
73
+ const queryResults = results.queryResults[0];
74
+ if (queryResults.rows) {
75
+ response.metadata.rows = queryResults.rows;
76
+ }
77
+ if (queryResults.fields) {
78
+ response.metadata.fields = queryResults.fields;
79
+ }
80
+ }
81
+ return {
82
+ data: response.metadata || null,
83
+ queries: results,
84
+ status: "success",
85
+ };
86
+ } catch (err) {
87
+ return { status: "error", error: (err as any).message };
88
+ }
89
+ }
90
+
91
+ private async runQueries(
92
+ queries: string[] | undefined,
93
+ runQueryConfig?: AdditionalProcessing
94
+ ) {
95
+ let results: any;
96
+ if (!queries) return { ...results, queryResults: [] };
97
+ if (runQueryConfig?.arrayToMap) {
98
+ return {
99
+ ...results,
100
+ mappedQueries: await mapQueries(
101
+ queries,
102
+ runQueryConfig.arrayToMap,
103
+ this.targetPool
104
+ ),
105
+ };
106
+ } else {
107
+ const queryResults = await Promise.all(
108
+ queries.map(async (query) => {
109
+ return await this.targetPool.query(query);
110
+ })
111
+ );
112
+ results = { ...results, queryResults };
113
+ if (runQueryConfig?.getSchema) {
114
+ results = {
115
+ ...results,
116
+ columns: await getTableSchema(queryResults[0], this.targetPool),
117
+ };
118
+ }
119
+ if (runQueryConfig?.removeFields) {
120
+ results = {
121
+ ...results,
122
+ queryResults: removeFields(queryResults, runQueryConfig.removeFields),
123
+ };
124
+ }
125
+ }
126
+ return results;
127
+ }
128
+
129
+ private async postQuill(
130
+ path: string,
131
+ payload: any
132
+ ): Promise<QuillClientResponse> {
133
+ const response = await axios.post(
134
+ `${this.baseUrl}/sdk/${path}`,
135
+ payload,
136
+ this.config
137
+ );
138
+ return response.data;
139
+ }
140
+
141
+ public async close() {
142
+ await this.targetPool.close();
143
+ }
144
+ }
@@ -0,0 +1,38 @@
1
+ import Quill from ".";
2
+
3
+ jest.mock(".");
4
+
5
+ describe("Quill", () => {
6
+ let quill: Quill;
7
+
8
+ beforeEach(() => {
9
+ quill = new Quill("dummy_private_key", "dummy_db_url");
10
+ quill.targetPool.query = jest.fn().mockResolvedValue([]);
11
+ });
12
+
13
+ describe("query", () => {
14
+ it("return nothing when suppling no queries", () => {
15
+ const metadata = {
16
+ task: "test",
17
+ queries: [],
18
+ };
19
+ const result = quill.query({
20
+ orgId: "dummy",
21
+ metadata,
22
+ });
23
+ expect(result).resolves.toEqual([]);
24
+ });
25
+ it("returns an error for the improper query", () => {
26
+ const metadata = {
27
+ task: "test",
28
+ queries: ["SELECT * FROM test"],
29
+ };
30
+ const result = quill.query({
31
+ orgId: "dummy",
32
+ metadata,
33
+ });
34
+ });
35
+ });
36
+
37
+ // Add more test cases as needed
38
+ });
@@ -0,0 +1,18 @@
1
+ export interface Mapable {
2
+ get(key: string): Promise<string | null>;
3
+ set(
4
+ key: string,
5
+ value: string,
6
+ type?: string,
7
+ ttl?: number
8
+ ): Promise<string | null>;
9
+ }
10
+
11
+ export interface CacheCredentials {
12
+ username: string;
13
+ password: string;
14
+ host: string;
15
+ port: string;
16
+ cacheType: string;
17
+ ttl?: number;
18
+ }
@@ -0,0 +1,5 @@
1
+ export interface DatabaseCredentials {
2
+ databaseConnectionString: string;
3
+ stagingDatabaseConnectionString: string;
4
+ databaseType: string;
5
+ }
@@ -0,0 +1,19 @@
1
+ export type FieldFormat =
2
+ | "whole_number"
3
+ | "one_decimal_place"
4
+ | "two_decimal_places"
5
+ | "dollar_amount"
6
+ | "MMM_yyyy"
7
+ | "MMM_dd_yyyy"
8
+ | "MMM_dd-MMM_dd"
9
+ | "MMM_dd_hh:mm_ap_pm"
10
+ | "hh_ap_pm"
11
+ | "percent"
12
+ | "string";
13
+
14
+ export interface FormattedColumn {
15
+ label: string;
16
+ field: string;
17
+ chartType: string;
18
+ format: FieldFormat;
19
+ }
@@ -0,0 +1,68 @@
1
+ import { CachedPool } from "../db/CachedPools";
2
+ import { CacheCredentials } from "./Cache";
3
+ import { DatabaseCredentials } from "./Database";
4
+ import { FieldFormat, FormattedColumn } from "./Formats";
5
+
6
+ export interface QuillRequestMetadata {
7
+ task: string;
8
+ // a query to be run
9
+ queries?: string[];
10
+ preQueries?: string[];
11
+ query?: string;
12
+ // a report to be fetched
13
+ id?: string;
14
+ filters?: any[];
15
+ // dashboard item fields
16
+ name?: string;
17
+ xAxisField?: string;
18
+ yAxisFields?: FormattedColumn[];
19
+ xAxisLabel?: string;
20
+ xAxisFormat?: FieldFormat;
21
+ yAxisLabel?: string;
22
+ chartType?: string;
23
+ dashboardName?: string;
24
+ columns?: FormattedColumn[];
25
+ dateField?: { table: string; field: string };
26
+ template?: boolean;
27
+ clientId?: string;
28
+ deleted?: boolean;
29
+ }
30
+
31
+ export interface QuillQueryParams {
32
+ orgId: string;
33
+ metadata: QuillRequestMetadata;
34
+ environment?: string;
35
+ }
36
+
37
+ export interface QuillTaskHandlerParams extends QuillQueryParams {
38
+ privateKey: string;
39
+ targetPool: CachedPool;
40
+ }
41
+
42
+ export interface QuillConfig {
43
+ privateKey: string;
44
+ db: Partial<DatabaseCredentials>;
45
+ cache: Partial<CacheCredentials>;
46
+
47
+ /**
48
+ * @deprecated Use db credential object instead
49
+ */
50
+ databaseConnectionString?: string;
51
+
52
+ /**
53
+ * @deprecated Use db credential object instead
54
+ */
55
+ stagingDatabaseConnectionString?: string;
56
+ }
57
+
58
+ export interface AdditionalProcessing {
59
+ getSchema?: boolean;
60
+ removeFields?: string[];
61
+ arrayToMap?: { arr: any; field: string };
62
+ }
63
+
64
+ export interface QuillClientResponse {
65
+ queries: string[];
66
+ metadata: any;
67
+ runQueryConfig: AdditionalProcessing;
68
+ }
@@ -0,0 +1,21 @@
1
+ export class PgError extends Error {
2
+ code?: string;
3
+ detail?: string;
4
+ hint?: string;
5
+ position?: string;
6
+ // Add other properties if needed
7
+ }
8
+
9
+ export function isSuperset(obj: any, baseClass: any): boolean {
10
+ // Get the property names of the base class
11
+ const baseProps = Object.getOwnPropertyNames(baseClass.prototype);
12
+
13
+ // Check if the object has all the properties of the base class
14
+ for (const prop of baseProps) {
15
+ if (!obj.hasOwnProperty(prop)) {
16
+ return false;
17
+ }
18
+ }
19
+
20
+ return true;
21
+ }
@@ -0,0 +1,58 @@
1
+ import { CachedPool } from "../db/CachedPools";
2
+
3
+ interface TableSchemaInfo {
4
+ fieldType: string;
5
+ name: string;
6
+ displayName: string;
7
+ isVisible: boolean;
8
+ }
9
+
10
+ export async function getTableSchema(
11
+ queryResults: any,
12
+ targetPool: CachedPool
13
+ ) {
14
+ const typesQuery = await targetPool.query(
15
+ "select typname, oid, typarray from pg_type order by oid;"
16
+ );
17
+ const schema: TableSchemaInfo[] = queryResults[0].fields.map(
18
+ (field: { dataTypeID: any; name: any }) => {
19
+ return {
20
+ fieldType: typesQuery.rows.filter(
21
+ (type: { oid: any }) => field.dataTypeID === type.oid
22
+ )[0].typname,
23
+ name: field.name,
24
+ displayName: field.name,
25
+ isVisible: true,
26
+ };
27
+ }
28
+ );
29
+ return schema;
30
+ }
31
+
32
+ export function removeFields(queryResults: any, fieldsToRemove: string[]): any {
33
+ const fields = queryResults.fields.filter((field: { name: any }) =>
34
+ fieldsToRemove.includes(field.name)
35
+ );
36
+ const rows = queryResults.map((row: any) => {
37
+ fieldsToRemove.forEach((field) => {
38
+ delete row[field];
39
+ });
40
+ return { fields, rows };
41
+ });
42
+ }
43
+
44
+ export async function mapQueries(
45
+ queries: string[],
46
+ arrayToMap: { arr: any; field: string },
47
+ targetPool: CachedPool
48
+ ) {
49
+ let arrayToMapResult = [];
50
+ for (let i = 0; i < queries.length; i++) {
51
+ const queryResult = await targetPool.query(queries[i]);
52
+ arrayToMapResult.push({
53
+ ...arrayToMap.arr[i],
54
+ [arrayToMap.field]: queryResult.rows,
55
+ });
56
+ }
57
+ return arrayToMapResult;
58
+ }
package/tsconfig.json CHANGED
@@ -1,109 +1,14 @@
1
1
  {
2
2
  "compilerOptions": {
3
- /* Visit https://aka.ms/tsconfig to read more about this file */
4
-
5
- /* Projects */
6
- // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
7
- // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
8
- // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
9
- // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
10
- // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
11
- // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
12
-
13
- /* Language and Environment */
14
- "target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
15
- // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
16
- // "jsx": "preserve", /* Specify what JSX code is generated. */
17
- // "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */
18
- // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
19
- // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
20
- // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
21
- // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
22
- // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
23
- // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
24
- // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
25
- // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
26
-
27
- /* Modules */
28
- "module": "commonjs", /* Specify what module code is generated. */
29
- // "rootDir": "./", /* Specify the root folder within your source files. */
30
- // "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */
31
- // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
32
- // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
33
- // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
34
- // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
35
- // "types": [], /* Specify type package names to be included without being referenced in a source file. */
36
- // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
37
- // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
38
- // "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */
39
- // "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */
40
- // "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */
41
- // "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
42
- // "resolveJsonModule": true, /* Enable importing .json files. */
43
- // "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */
44
- // "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
45
-
46
- /* JavaScript Support */
47
- // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
48
- // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
49
- // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
50
-
51
- /* Emit */
52
- // "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
53
- // "declarationMap": true, /* Create sourcemaps for d.ts files. */
54
- // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
55
- // "sourceMap": true, /* Create source map files for emitted JavaScript files. */
56
- // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
57
- // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
58
- // "outDir": "./", /* Specify an output folder for all emitted files. */
59
- // "removeComments": true, /* Disable emitting comments. */
60
- // "noEmit": true, /* Disable emitting files from a compilation. */
61
- // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
62
- // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */
63
- // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
64
- // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
65
- // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
66
- // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
67
- // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
68
- // "newLine": "crlf", /* Set the newline character for emitting files. */
69
- // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
70
- // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
71
- // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
72
- // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
73
- // "declarationDir": "./", /* Specify the output directory for generated declaration files. */
74
- // "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
75
-
76
- /* Interop Constraints */
77
- // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
78
- // "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */
79
- // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
80
- "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
81
- // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
82
- "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
83
-
84
- /* Type Checking */
85
- "strict": true, /* Enable all strict type-checking options. */
86
- // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
87
- // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
88
- // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
89
- // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
90
- // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
91
- // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
92
- // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
93
- // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
94
- // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
95
- // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
96
- // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
97
- // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
98
- // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
99
- // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
100
- // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
101
- // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
102
- // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
103
- // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
104
-
105
- /* Completeness */
106
- // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
107
- "skipLibCheck": true /* Skip type checking all .d.ts files. */
108
- }
3
+ "target": "es2016",
4
+ "module": "commonjs",
5
+ "esModuleInterop": true,
6
+ "forceConsistentCasingInFileNames": true,
7
+ "strict": true,
8
+ "skipLibCheck": true,
9
+ "outDir": "./dist",
10
+ "rootDir": "./src"
11
+ },
12
+ "include": ["src/**/*.ts"],
13
+ "exclude": ["node_modules", "**/*.spec.ts"]
109
14
  }
package/.gitattributes DELETED
@@ -1,2 +0,0 @@
1
- # Auto detect text files and perform LF normalization
2
- * text=auto
package/LICENSE DELETED
@@ -1,21 +0,0 @@
1
- MIT License
2
-
3
- Copyright (c) 2023 stryvedev
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
package/index.js DELETED
@@ -1,172 +0,0 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- const { Pool, Connection } = require("pg");
12
- const axios = require("axios");
13
- var PgError = require("pg-error");
14
- Connection.prototype.parseE = PgError.parse;
15
- Connection.prototype.parseN = PgError.parse;
16
- const cache = {}; //set the cache
17
- function setCache(key, value) {
18
- cache[key] = value;
19
- }
20
- function getCache(key) {
21
- return cache[key];
22
- }
23
- module.exports = ({ privateKey, databaseConnectionString, stagingDatabaseConnectionString, }) => {
24
- const pool = new Pool({
25
- connectionString: databaseConnectionString,
26
- ssl: { rejectUnauthorized: false }
27
- });
28
- const stagingPool = new Pool({
29
- connectionString: stagingDatabaseConnectionString,
30
- });
31
- return {
32
- query: ({ orgId, metadata, environment }) => __awaiter(void 0, void 0, void 0, function* () {
33
- const targetPool = environment === "STAGING" ? stagingPool : pool;
34
- const { task, query, id } = metadata;
35
- if (task === "query") {
36
- try {
37
- const response = yield axios.post("https://quill-344421.uc.r.appspot.com/validate", { query: query }, {
38
- params: {
39
- orgId,
40
- },
41
- headers: {
42
- Authorization: `Bearer ${privateKey}`,
43
- },
44
- });
45
- const { fieldToRemove } = response.data;
46
- const queryResult = yield targetPool.query(response.data.query);
47
- return Object.assign(Object.assign({}, queryResult), { fields: queryResult.fields.filter(
48
- // @ts-ignore
49
- (field) => field.name !== fieldToRemove),
50
- // @ts-ignore
51
- rows: queryResult.rows.map((row) => {
52
- delete row[fieldToRemove];
53
- return row;
54
- }) });
55
- }
56
- catch (err) {
57
- return Object.assign(Object.assign({}, err), {
58
- // @ts-ignore
59
- errorMessage: err && err.message ? err.message : "" });
60
- }
61
- }
62
- if (task === "config") {
63
- try {
64
- const response = yield axios.get("https://quill-344421.uc.r.appspot.com/config", {
65
- params: {
66
- orgId,
67
- // @ts-ignore
68
- name: metadata === null || metadata === void 0 ? void 0 : metadata.name,
69
- },
70
- headers: {
71
- Authorization: `Bearer ${privateKey}`,
72
- },
73
- });
74
- let dashConfig = response.data;
75
- let newFilters = [];
76
- if (dashConfig.filters && dashConfig.filters.length) {
77
- for (let i = 0; i < dashConfig.filters.length; i++) {
78
- const queryResult = yield targetPool.query(dashConfig.filters[i].query);
79
- const { rows } = queryResult;
80
- newFilters.push(Object.assign(Object.assign({}, dashConfig.filters[i]), { options: rows }));
81
- dashConfig.filters[i].options = rows;
82
- }
83
- }
84
- dashConfig = Object.assign(Object.assign({}, dashConfig), { filters: newFilters });
85
- const { fieldToRemove, newQueries } = response.data;
86
- if (newQueries) {
87
- for (const newQuery of newQueries) {
88
- const { query } = newQuery;
89
- const cacheKey = `config:${orgId}:${newQuery._id}}`;
90
- setCache(cacheKey, { fieldToRemove, query });
91
- }
92
- ;
93
- }
94
- return Object.assign({}, dashConfig);
95
- }
96
- catch (_a) {
97
- return Object.assign(Object.assign({}, err), {
98
- // @ts-ignore
99
- errorMessage: err && err.message ? err.message : "" });
100
- }
101
- }
102
- if (task === "create") {
103
- try {
104
- const response = yield axios.post("https://quill-344421.uc.r.appspot.com/item", Object.assign({}, metadata), {
105
- params: {
106
- orgId,
107
- query
108
- },
109
- headers: {
110
- Authorization: `Bearer ${privateKey}`,
111
- },
112
- });
113
- return response.data;
114
- }
115
- catch (_b) {
116
- return Object.assign(Object.assign({}, err), {
117
- // @ts-ignore
118
- errorMessage: err && err.message ? err.message : "" });
119
- }
120
- }
121
- if (task === "item") {
122
- try {
123
- const { filters } = metadata;
124
- const resp = yield axios.get("https://quill-344421.uc.r.appspot.com/selfhostitem", {
125
- params: {
126
- id,
127
- orgId,
128
- },
129
- headers: {
130
- Authorization: `Bearer ${privateKey}`,
131
- },
132
- });
133
- let fieldToRemove, query;
134
- if (false && getCache(`config:${orgId}:${id}:${JSON.stringify(filters)}`)) {
135
- ({ fieldToRemove, query } = getCache(`config:${orgId}:${id}:${JSON.stringify(filters)}`));
136
- }
137
- else {
138
- const response = yield axios.post("https://quill-344421.uc.r.appspot.com/validate", {
139
- dashboardItemId: id,
140
- query: resp.data.queryString,
141
- filters: filters,
142
- orgId: orgId
143
- }, {
144
- headers: {
145
- Authorization: `Bearer ${privateKey}`
146
- }
147
- });
148
- ({ fieldToRemove, query } = response.data);
149
- const cacheKey = `config:${orgId}:${id}:${JSON.stringify(filters)}`;
150
- setCache(cacheKey, { fieldToRemove, query });
151
- }
152
- ;
153
- const queryResult = yield targetPool.query(query);
154
- return Object.assign(Object.assign({}, resp.data), { fields: queryResult.fields
155
- .filter(
156
- // @ts-ignore
157
- (field) => field.name !== fieldToRemove),
158
- // @ts-ignore
159
- rows: queryResult.rows.map((row) => {
160
- delete row[fieldToRemove];
161
- return row;
162
- }) });
163
- }
164
- catch (err) {
165
- return Object.assign(Object.assign({}, err), {
166
- // @ts-ignore
167
- errorMessage: err && err.message ? err.message : "" });
168
- }
169
- }
170
- }),
171
- };
172
- };
package/index.ts DELETED
@@ -1,278 +0,0 @@
1
- const { Pool, Connection } = require("pg");
2
- const axios = require("axios");
3
- var PgError = require("pg-error");
4
- Connection.prototype.parseE = PgError.parse;
5
- Connection.prototype.parseN = PgError.parse;
6
-
7
- const cache : any = {}; //set the cache
8
-
9
- function setCache(key : any, value : any) {
10
- cache[key] = value;
11
- }
12
-
13
- function getCache(key : any) {
14
- return cache[key];
15
- }
16
-
17
- interface QuillConfig {
18
- privateKey: string;
19
- databaseConnectionString: string;
20
- stagingDatabaseConnectionString?: string;
21
- }
22
-
23
- type FieldFormat =
24
- | "whole_number"
25
- | "one_decimal_place"
26
- | "two_decimal_places"
27
- | "dollar_amount"
28
- | "MMM_yyyy"
29
- | "MMM_dd_yyyy"
30
- | "MMM_dd-MMM_dd"
31
- | "MMM_dd_hh:mm_ap_pm"
32
- | "hh_ap_pm"
33
- | "percent"
34
- | "string";
35
- interface FormattedColumn {
36
- label: string;
37
- field: string;
38
- chartType: string;
39
- format: FieldFormat;
40
- }
41
- interface QuillRequestMetadata {
42
- task: string;
43
- // a query to be run
44
- query?: string;
45
- // a report to be fetched
46
- id?: string;
47
- filters?: any[];
48
- // dashboard item fields
49
- name?: string;
50
- xAxisField?: string;
51
- yAxisFields?: FormattedColumn[];
52
- xAxisLabel?: string;
53
- xAxisFormat?: FieldFormat;
54
- yAxisLabel?: string;
55
- chartType?: string;
56
- dashboardName?: string;
57
- columns?: FormattedColumn[];
58
- dateField?: { table: string; field: string };
59
- template?: boolean;
60
- }
61
- interface QuillQueryParams {
62
- orgId: string;
63
- metadata: QuillRequestMetadata;
64
- environment?: string;
65
- }
66
- module.exports = ({
67
- privateKey,
68
- databaseConnectionString,
69
- stagingDatabaseConnectionString,
70
- }: QuillConfig) => {
71
- const pool = new Pool({
72
- connectionString: databaseConnectionString,
73
- ssl: {rejectUnauthorized: false}
74
- });
75
- const stagingPool = new Pool({
76
- connectionString: stagingDatabaseConnectionString,
77
- });
78
- return {
79
- query: async ({ orgId, metadata, environment }: QuillQueryParams) => {
80
- const targetPool = environment === "STAGING" ? stagingPool : pool;
81
- const { task, query, id } = metadata;
82
-
83
- if (task === "query") {
84
- try {
85
- const response = await axios.post(
86
- "https://quill-344421.uc.r.appspot.com/validate",
87
- { query: query },
88
- {
89
- params: {
90
- orgId,
91
- },
92
- headers: {
93
- Authorization: `Bearer ${privateKey}`,
94
- },
95
- }
96
- );
97
- const { fieldToRemove } = response.data;
98
- const queryResult = await targetPool.query(response.data.query);
99
- return {
100
- ...queryResult,
101
- fields: queryResult.fields.filter(
102
- // @ts-ignore
103
- (field) => field.name !== fieldToRemove
104
- ),
105
- // @ts-ignore
106
- rows: queryResult.rows.map((row) => {
107
- delete row[fieldToRemove];
108
- return row;
109
- }),
110
- };
111
- } catch (err) {
112
- return {
113
- // @ts-ignore
114
- ...err,
115
- // @ts-ignore
116
- errorMessage: err && err.message ? err.message : "",
117
- };
118
- }
119
- }
120
- if (task === "config") {
121
- try {
122
- const response = await axios.get(
123
- "https://quill-344421.uc.r.appspot.com/config",
124
- {
125
- params: {
126
- orgId,
127
- // @ts-ignore
128
- name: metadata?.name,
129
- },
130
- headers: {
131
- Authorization: `Bearer ${privateKey}`,
132
- },
133
- }
134
- );
135
- let dashConfig = response.data;
136
- let newFilters = [];
137
-
138
-
139
- if (dashConfig.filters && dashConfig.filters.length) {
140
- for (let i = 0; i < dashConfig.filters.length; i++) {
141
- const queryResult = await targetPool.query(
142
- dashConfig.filters[i].query
143
- );
144
- const { rows } = queryResult;
145
- newFilters.push({ ...dashConfig.filters[i], options: rows });
146
- dashConfig.filters[i].options = rows
147
- }
148
-
149
- }
150
-
151
- dashConfig = { ...dashConfig, filters: newFilters };
152
-
153
- const { fieldToRemove, newQueries } = response.data;
154
-
155
- if (newQueries) {
156
- for (const newQuery of newQueries) {
157
- const { query } = newQuery
158
- const cacheKey = `config:${orgId}:${newQuery._id}}`;
159
- setCache(cacheKey, {fieldToRemove, query});
160
- };
161
- }
162
-
163
- return {
164
- ...dashConfig
165
- };
166
-
167
- }
168
- catch {
169
- return {
170
- // @ts-ignore
171
- ...err,
172
- // @ts-ignore
173
- errorMessage: err && err.message ? err.message : "",
174
- };
175
- }
176
- }
177
-
178
- if (task === "create") {
179
- try {
180
- const response = await axios.post(
181
- "https://quill-344421.uc.r.appspot.com/item",
182
- { ...metadata },
183
- {
184
- params: {
185
- orgId,
186
- query
187
- },
188
- headers: {
189
- Authorization: `Bearer ${privateKey}`,
190
- },
191
- }
192
- );
193
- return response.data;
194
- }
195
- catch {
196
- return {
197
- // @ts-ignore
198
- ...err,
199
- // @ts-ignore
200
- errorMessage: err && err.message ? err.message : "",
201
- };
202
- }
203
- }
204
-
205
- if (task === "item") {
206
- try {
207
-
208
- const {filters } = metadata;
209
- const resp = await axios.get(
210
- "https://quill-344421.uc.r.appspot.com/selfhostitem",
211
- {
212
- params: {
213
- id,
214
- orgId,
215
- },
216
- headers: {
217
- Authorization: `Bearer ${privateKey}`,
218
- },
219
- }
220
- );
221
- let fieldToRemove : any, query;
222
-
223
-
224
- if (false && getCache(`config:${orgId}:${id}:${JSON.stringify(filters)}`)) {
225
- ({fieldToRemove, query} = getCache(`config:${orgId}:${id}:${JSON.stringify(filters)}`));
226
- }
227
- else {
228
- const response = await axios.post(
229
- "https://quill-344421.uc.r.appspot.com/validate",
230
- {
231
- dashboardItemId: id,
232
- query: resp.data.queryString,
233
- filters: filters,
234
- orgId: orgId
235
- },
236
- {
237
- headers: {
238
- Authorization: `Bearer ${privateKey}`
239
- }
240
- }
241
- );
242
-
243
-
244
-
245
- ({ fieldToRemove, query } = response.data);
246
-
247
- const cacheKey = `config:${orgId}:${id}:${JSON.stringify(filters)}`;
248
- setCache(cacheKey, {fieldToRemove, query});
249
- };
250
-
251
- const queryResult = await targetPool.query(query);
252
-
253
- return {
254
- ...resp.data,
255
- fields: queryResult.fields
256
- .filter(
257
- // @ts-ignore
258
- (field) => field.name !== fieldToRemove
259
- ),
260
- // @ts-ignore
261
- rows: queryResult.rows.map((row) => {
262
- delete row[fieldToRemove];
263
- return row;
264
- }),
265
- };
266
-
267
- } catch (err) {
268
- return {
269
- // @ts-ignore
270
- ...err,
271
- // @ts-ignore
272
- errorMessage: err && err.message ? err.message : "",
273
- };
274
- }
275
- }
276
- },
277
- };
278
- };