@technicity/data-service-generator 0.13.26 → 0.14.0

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.
@@ -86,125 +86,137 @@ function getSqlAst(input) {
86
86
  args,
87
87
  where,
88
88
  orderBy,
89
- children: children.concat(fields.map((x) => {
90
- if (typeof x === "string") {
91
- const mappedField = tableArtifacts.mappedFields?.[x];
92
- if (mappedField != null) {
93
- return {
94
- type: "expression",
95
- sqlExpr: (table) => {
96
- const referencedTableAlias = namespace.generate("table", mappedField.referencedTable);
97
- return format(`(SELECT ?? FROM ?? AS ?? WHERE ??.?? = ${table}.??)`, [
98
- mappedField.name,
99
- mappedField.referencedTable,
100
- referencedTableAlias,
101
- referencedTableAlias,
102
- mappedField.referencedKey,
103
- mappedField.foreignKey
104
- ]);
89
+ children: children.concat(Object.entries(fields)
90
+ .filter(([_, v]) => v !== false)
91
+ .map(([k, v]) => {
92
+ const mappedField = tableArtifacts.mappedFields?.[k];
93
+ const relationField = tableArtifacts.relationFields?.[k];
94
+ if (mappedField != null) {
95
+ return {
96
+ type: "expression",
97
+ sqlExpr: (table) => {
98
+ const referencedTableAlias = namespace.generate("table", mappedField.referencedTable);
99
+ return format(`(SELECT ?? FROM ?? AS ?? WHERE ??.?? = ${table}.??)`, [
100
+ mappedField.name,
101
+ mappedField.referencedTable,
102
+ referencedTableAlias,
103
+ referencedTableAlias,
104
+ mappedField.referencedKey,
105
+ mappedField.foreignKey
106
+ ]);
107
+ },
108
+ name: k,
109
+ fieldName: k,
110
+ as: namespace.generate("column", k)
111
+ };
112
+ }
113
+ else if (relationField != null) {
114
+ const fields = typeof v === "object"
115
+ ? v.$fields ??
116
+ tableArtifacts.scalarFields.reduce((acc, x) => {
117
+ acc[x] = true;
118
+ return acc;
119
+ }, {})
120
+ : tableArtifacts.scalarFields.reduce((acc, x) => {
121
+ acc[x] = true;
122
+ return acc;
123
+ }, {});
124
+ const args = typeof v === "object" ? v : {};
125
+ if (relationField.type === "many-to-many") {
126
+ const asJunction = namespace.generate("table", relationField.junctionTable);
127
+ const uniqueKey = artifacts[relationField.junctionTable].primaryKey;
128
+ return getSqlAst({
129
+ table: relationField.table,
130
+ fieldName: k,
131
+ fields,
132
+ args,
133
+ grabMany: relationField.grabMany,
134
+ firstChild: {
135
+ ...keyToASTChild(uniqueKey, namespace, asJunction),
136
+ // There's either a bug in join-monster, or join-monster doesn't expect a junction table to have a primary key.
137
+ // Work around by ensuring a unique name, to avoid e.g. SELECT `UserRole`.`id` AS `b`, `Role`.`id` AS `b`
138
+ // Notice the duplicate names in the select. This results in missing rows because the
139
+ // shape definition passed into NestHydrationJS will only have 1 `id`.
140
+ fieldName: String(Date.now()),
141
+ as: String(Date.now())
142
+ },
143
+ junction: {
144
+ sqlTable: relationField.junctionTable,
145
+ as: asJunction,
146
+ uniqueKey,
147
+ where: (table, args) => {
148
+ if (typeof args?.$where !== "object" ||
149
+ typeof args?.$where == null ||
150
+ args.$where[relationField.junctionTable] == null) {
151
+ return undefined;
152
+ }
153
+ const argsMapped = _.cloneDeep(args);
154
+ argsMapped.$where =
155
+ argsMapped.$where[relationField.junctionTable];
156
+ const whereResult = getWhere(
157
+ // table is escaped already
158
+ table, argsMapped, dialect, orderBy, rowWithMatchingCursor);
159
+ if (whereResult == null) {
160
+ return undefined;
161
+ }
162
+ return whereResult;
163
+ },
164
+ // Because we used the where in sqlJoin
165
+ // where: () => undefined,
166
+ // TODO - where
167
+ // sqlJoins: [
168
+ // (t: string, junctionTable: string, args: any) =>
169
+ // `${t}.${relationField.relations[0].referencedKey} = ${junctionTable}.${relationField.relations[0].foreignKey}`,
170
+ // (junctionTable: string, t: string, args: any) =>
171
+ // `${junctionTable}.${relationField.relations[1].foreignKey} = ${t}.${relationField.relations[1].referencedKey}`,
172
+ // ],
173
+ // We have to use sqlBatch instead of sqlJoin because pagination is not
174
+ // supported with `mysql` dialect, and LIMITing the root list means
175
+ // sub lists are limited, too.
176
+ sqlBatch: {
177
+ thisKey: columnToASTChild(relationField.relations[0].foreignKey, namespace, asJunction),
178
+ parentKey: columnToASTChild(relationField.relations[0].referencedKey, namespace),
179
+ sqlJoin: (junctionTable, t, args) => `${junctionTable}.${relationField.relations[1].foreignKey} = ${t}.${relationField.relations[1].referencedKey}`
180
+ }
105
181
  },
106
- name: x,
107
- fieldName: x,
108
- as: namespace.generate("column", x)
109
- };
182
+ getWhere,
183
+ artifacts,
184
+ dialect
185
+ });
110
186
  }
111
- // TODO - validate in dev?
112
- return columnToASTChild(x, namespace);
113
- }
114
- const relationField = tableArtifacts.relationFields?.[x.name];
115
- if (relationField == null) {
116
- throw new Error("Invalid field: " + table + "." + x.name);
117
- }
118
- if (relationField.type === "many-to-many") {
119
- const asJunction = namespace.generate("table", relationField.junctionTable);
120
- const uniqueKey = artifacts[relationField.junctionTable].primaryKey;
121
187
  return getSqlAst({
122
188
  table: relationField.table,
123
- fieldName: x.as ?? x.name,
124
- fields: x.fields,
125
- args: x.args,
189
+ fieldName: k,
190
+ fields,
191
+ args,
126
192
  grabMany: relationField.grabMany,
127
- firstChild: {
128
- ...keyToASTChild(uniqueKey, namespace, asJunction),
129
- // There's either a bug in join-monster, or join-monster doesn't expect a junction table to have a primary key.
130
- // Work around by ensuring a unique name, to avoid e.g. SELECT `UserRole`.`id` AS `b`, `Role`.`id` AS `b`
131
- // Notice the duplicate names in the select. This results in missing rows because the
132
- // shape definition passed into NestHydrationJS will only have 1 `id`.
133
- fieldName: String(Date.now()),
134
- as: String(Date.now())
135
- },
136
- junction: {
137
- sqlTable: relationField.junctionTable,
138
- as: asJunction,
139
- uniqueKey,
140
- where: (table, args) => {
141
- if (typeof args?.$where !== "object" ||
142
- typeof args?.$where == null ||
143
- args.$where[relationField.junctionTable] == null) {
144
- return undefined;
145
- }
146
- const argsMapped = _.cloneDeep(args);
147
- argsMapped.$where = argsMapped.$where[relationField.junctionTable];
148
- const whereResult = getWhere(
149
- // table is escaped already
150
- table, argsMapped, dialect, orderBy, rowWithMatchingCursor);
151
- if (whereResult == null) {
152
- return undefined;
153
- }
154
- return whereResult;
155
- },
156
- // Because we used the where in sqlJoin
157
- // where: () => undefined,
158
- // TODO - where
159
- // sqlJoins: [
160
- // (t: string, junctionTable: string, args: any) =>
161
- // `${t}.${relationField.relations[0].referencedKey} = ${junctionTable}.${relationField.relations[0].foreignKey}`,
162
- // (junctionTable: string, t: string, args: any) =>
163
- // `${junctionTable}.${relationField.relations[1].foreignKey} = ${t}.${relationField.relations[1].referencedKey}`,
164
- // ],
165
- // We have to use sqlBatch instead of sqlJoin because pagination is not
166
- // supported with `mysql` dialect, and LIMITing the root list means
167
- // sub lists are limited, too.
168
- sqlBatch: {
169
- thisKey: columnToASTChild(relationField.relations[0].foreignKey, namespace, asJunction),
170
- parentKey: columnToASTChild(relationField.relations[0].referencedKey, namespace),
171
- sqlJoin: (junctionTable, t, args) => `${junctionTable}.${relationField.relations[1].foreignKey} = ${t}.${relationField.relations[1].referencedKey}`
172
- }
193
+ // Because we used the where in sqlJoin
194
+ // where: () => undefined,
195
+ // sqlJoin: (t1: string, t2: string, args: any) => {
196
+ // let sql = `${t1}.?? = ${t2}.??`;
197
+ // let values = [relationField.relation.foreignKey, relationField.relation.referencedKey];
198
+ // if (args?.$where != null) {
199
+ // const whereResult = getWhere(t2, args);
200
+ // sql += " and " + whereResult.sql;
201
+ // values.push(whereResult.values);
202
+ // }
203
+ // return s.format(sql, values);
204
+ // },
205
+ // We have to use sqlBatch instead of sqlJoin because pagination is not
206
+ // supported with `mysql` dialect, and LIMITing the root list means
207
+ // sub lists are limited, too.
208
+ sqlBatch: {
209
+ thisKey: columnToASTChild(relationField.relation.referencedKey, namespace),
210
+ parentKey: columnToASTChild(relationField.relation.foreignKey, namespace)
173
211
  },
174
212
  getWhere,
175
213
  artifacts,
176
214
  dialect
177
215
  });
178
216
  }
179
- return getSqlAst({
180
- table: relationField.table,
181
- fieldName: x.as ?? x.name,
182
- fields: x.fields,
183
- args: x.args,
184
- grabMany: relationField.grabMany,
185
- // Because we used the where in sqlJoin
186
- // where: () => undefined,
187
- // sqlJoin: (t1: string, t2: string, args: any) => {
188
- // let sql = `${t1}.?? = ${t2}.??`;
189
- // let values = [relationField.relation.foreignKey, relationField.relation.referencedKey];
190
- // if (args?.$where != null) {
191
- // const whereResult = getWhere(t2, args);
192
- // sql += " and " + whereResult.sql;
193
- // values.push(whereResult.values);
194
- // }
195
- // return s.format(sql, values);
196
- // },
197
- // We have to use sqlBatch instead of sqlJoin because pagination is not
198
- // supported with `mysql` dialect, and LIMITing the root list means
199
- // sub lists are limited, too.
200
- sqlBatch: {
201
- thisKey: columnToASTChild(relationField.relation.referencedKey, namespace),
202
- parentKey: columnToASTChild(relationField.relation.foreignKey, namespace)
203
- },
204
- getWhere,
205
- artifacts,
206
- dialect
207
- });
217
+ else {
218
+ return columnToASTChild(k, namespace);
219
+ }
208
220
  }))
209
221
  };
210
222
  }
@@ -1,5 +1,4 @@
1
- import type { IGetSQLASTInput, IArtifacts, IDialect, TDbCall, TFormatQuery, TBeginTransaction, TContext } from "../IRuntime";
2
- import type { TMiddleware, TResolveParams } from "../IRuntime";
1
+ import type { IGetSQLASTInput, IArtifacts, IDialect, TDbCall, TFormatQuery, TBeginTransaction, TContext, TMiddleware, TResolveParams } from "../IRuntime";
3
2
  import Cache from "../Cache";
4
3
  export declare function resolve(input: TResolveParams, dbCall: TDbCall, formatQuery: TFormatQuery, beginTransaction: TBeginTransaction, dialect: IDialect, middlewareHandler: MiddlewareHandler<TMiddleware>, context: TContext, cache?: Cache): Promise<any>;
5
4
  export declare class MiddlewareHandler<M extends Function> {
@@ -42,7 +42,6 @@ const getSqlAst_1 = require("./getSqlAst");
42
42
  const getWhere_1 = require("./getWhere");
43
43
  const getDateTimeStringMySQL_1 = require("./getDateTimeStringMySQL");
44
44
  const cursor_1 = require("./cursor");
45
- const runTransforms_1 = require("./runTransforms");
46
45
  const addNullFallbacks_1 = require("./addNullFallbacks");
47
46
  const SDKNotFoundError_1 = require("./SDKNotFoundError");
48
47
  const SDKBadWhereError_1 = require("./SDKBadWhereError");
@@ -160,7 +159,11 @@ async function getData(input, dbCall, formatQuery, dialect) {
160
159
  }
161
160
  // we need to read the query AST and build a new "SQL AST" from which the SQL and
162
161
  // const sqlAST = queryAST.queryASTToSqlAST(resolveInfo, options, context);
163
- const fields = input.fields ?? getScalarFields(input.resource, input.artifacts);
162
+ const fields = input.fields ??
163
+ getScalarFields(input.resource, input.artifacts).reduce((acc, x) => {
164
+ acc[x] = true;
165
+ return acc;
166
+ }, {});
164
167
  const orderByListPaginatedRootResult =
165
168
  // MSSQL's OFFSET and FETCH requires ORDER BY, so we need to provide a fallback
166
169
  dialect === "mssql" && paginationType === "limit-offset"
@@ -267,7 +270,7 @@ async function getData(input, dbCall, formatQuery, dialect) {
267
270
  fieldName: "data",
268
271
  args: argsTotalCount,
269
272
  // Because we're going to manually set children anyway
270
- fields: [],
273
+ fields: {},
271
274
  getWhere: getWhere_1.getWhere,
272
275
  // We don't want the where clause to include cursor-related stuff
273
276
  rowWithMatchingCursor: null,
@@ -340,21 +343,23 @@ async function getCached(input, dbCall, formatQuery, dialect, cache) {
340
343
  function ensureUuidSelect(input) {
341
344
  const { resource, artifacts } = input;
342
345
  const remove = [];
343
- ensure(resource, input);
346
+ ensure(resource, input.fields);
344
347
  function ensure(type, input, path = []) {
345
348
  const { scalarFields, relationFields } = artifacts[type];
346
349
  if (!scalarFields.includes("uuid"))
347
350
  return;
348
- const fields = input.fields || [];
349
- if (!fields.includes("uuid")) {
351
+ const fields = input || {};
352
+ if (!Object.keys(fields).includes("uuid")) {
350
353
  remove.push(path);
351
- fields.unshift("uuid");
354
+ fields["uuid"] = true;
352
355
  }
353
- for (const field of fields)
354
- if (typeof field == "object") {
355
- const { name } = field;
356
- const { table } = relationFields[name];
357
- ensure(table, field, path.concat(name));
356
+ const entries = Object.entries(fields);
357
+ for (const [k, v] of entries)
358
+ if (typeof v === "object") {
359
+ const table = relationFields[k]?.table;
360
+ if (table != null) {
361
+ ensure(table, v.$fields, path.concat(k));
362
+ }
358
363
  }
359
364
  }
360
365
  return remove;
@@ -832,27 +837,17 @@ async function mapMappedFields(artifactsForTable, data, dbCall, formatQuery) {
832
837
  }
833
838
  }
834
839
  // 1. Remove additional keys added to data for batches and joins
835
- // 2. Execute `transform` functions if they exist
836
840
  function postProcess(data, fields, shouldRemoveExtraKeys) {
837
841
  if (shouldRemoveExtraKeys) {
838
842
  removeExtraKeys(data, fields);
839
843
  }
840
- (0, runTransforms_1.runTransforms)(data, fields);
841
844
  }
842
845
  exports.postProcess = postProcess;
843
846
  function removeExtraKeys(data, fields) {
844
847
  if (data == null || (Array.isArray(data) && data[0] == null)) {
845
848
  return;
846
849
  }
847
- let fieldKeys = [];
848
- for (let x of fields) {
849
- if (typeof x === "string") {
850
- fieldKeys.push(x);
851
- }
852
- else {
853
- fieldKeys.push(x.as ?? x.name);
854
- }
855
- }
850
+ let fieldKeys = Object.keys(fields);
856
851
  const dataKeys = Array.isArray(data) ? Object.keys(data[0]) : Object.keys(data);
857
852
  const extraDataKeys = _.difference(dataKeys, fieldKeys);
858
853
  for (let k of extraDataKeys) {
@@ -865,16 +860,16 @@ function removeExtraKeys(data, fields) {
865
860
  delete data[k];
866
861
  }
867
862
  }
868
- for (let x of fields) {
869
- if (typeof x === "object") {
870
- const k = x.as ?? x.name;
863
+ const entries = Object.entries(fields);
864
+ for (let [k, v] of entries) {
865
+ if (typeof v === "object" && v.$fields != null) {
871
866
  if (Array.isArray(data)) {
872
867
  for (let d of data) {
873
- removeExtraKeys(d[k], x.fields);
868
+ removeExtraKeys(d[k], v.$fields);
874
869
  }
875
870
  }
876
871
  else {
877
- removeExtraKeys(data[k], x.fields);
872
+ removeExtraKeys(data[k], v.$fields);
878
873
  }
879
874
  }
880
875
  }
@@ -902,11 +897,9 @@ function typeCastSqlite(data, fields, table, artifacts) {
902
897
  throw new Error(`Failed to resolve typeCastMap for table \`${table}\``);
903
898
  }
904
899
  if (booleanColumns.size > 0) {
905
- for (let field of fields) {
906
- const name = typeof field === "string" ? field : field.name;
907
- const as = typeof field === "string" ? undefined : field.as;
908
- if (booleanColumns.has(name)) {
909
- const k = as ?? name;
900
+ const keys = Object.keys(fields);
901
+ for (let k of keys) {
902
+ if (booleanColumns.has(k)) {
910
903
  if (Array.isArray(data)) {
911
904
  for (let d of data) {
912
905
  d[k] = !!d[k];
@@ -919,21 +912,25 @@ function typeCastSqlite(data, fields, table, artifacts) {
919
912
  }
920
913
  }
921
914
  const tableArtifacts = artifacts[table];
922
- for (let x of fields) {
923
- if (typeof x === "object") {
924
- const name = x.name;
925
- const relationFields = tableArtifacts.relationFields[name];
915
+ const entries = Object.entries(fields);
916
+ for (let [k, v] of entries) {
917
+ if (typeof v === "object") {
918
+ const relationFields = tableArtifacts.relationFields[k];
926
919
  if (relationFields == null) {
927
- throw new Error(`Failed to resolve relationFields for field \`${name}\``);
920
+ throw new Error(`Failed to resolve relationFields for field \`${k}\``);
928
921
  }
929
- const k = x.as ?? name;
922
+ const fields = v.$fields ??
923
+ tableArtifacts.scalarFields.reduce((acc, x) => {
924
+ acc[x] = true;
925
+ return acc;
926
+ }, {});
930
927
  if (Array.isArray(data)) {
931
928
  for (let d of data) {
932
- typeCastSqlite(d[k], x.fields, relationFields.table, artifacts);
929
+ typeCastSqlite(d[k], fields, relationFields.table, artifacts);
933
930
  }
934
931
  }
935
932
  else {
936
- typeCastSqlite(data[k], x.fields, relationFields.table, artifacts);
933
+ typeCastSqlite(data[k], fields, relationFields.table, artifacts);
937
934
  }
938
935
  }
939
936
  }
@@ -1,2 +1,2 @@
1
- import { IArgs, IField } from "./runtime/IRuntime";
2
- export declare function traverseFieldArgs(fields: IField[], cb: (args: IArgs | undefined) => IArgs): void;
1
+ import { IArgs, TSelect } from "./runtime/IRuntime";
2
+ export declare function traverseFieldArgs(fields: TSelect, cb: (args: IArgs | undefined) => IArgs): void;
@@ -2,12 +2,17 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.traverseFieldArgs = void 0;
4
4
  function traverseFieldArgs(fields, cb) {
5
- for (let x of fields) {
5
+ const values = Object.values(fields);
6
+ for (let x of values) {
6
7
  if (typeof x !== "object") {
7
8
  continue;
8
9
  }
9
- x.args = cb(x.args);
10
- traverseFieldArgs(x.fields, cb);
10
+ const fields = x.$fields;
11
+ if (fields == null) {
12
+ continue;
13
+ }
14
+ cb(x);
15
+ traverseFieldArgs(fields, cb);
11
16
  }
12
17
  }
13
18
  exports.traverseFieldArgs = traverseFieldArgs;
@@ -9,64 +9,48 @@ const _1 = require(".");
9
9
  const addWhereValidTrue_1 = require("../test/addWhereValidTrue");
10
10
  (0, globals_1.describe)("traverseFieldArgs", () => {
11
11
  (0, globals_1.test)("should work", () => {
12
- const fields = [
13
- "id",
14
- "uuid",
15
- {
16
- name: "business",
17
- fields: ["id", "uuid", "name"]
12
+ const fields = {
13
+ id: true,
14
+ uuid: true,
15
+ business: { $fields: { id: true, uuid: true, name: true } },
16
+ sessionList: {
17
+ $fields: {
18
+ id: true,
19
+ archived: true,
20
+ fooList: { $fields: { id: true, uuid: true } }
21
+ },
22
+ $where: { archived: false },
23
+ $orderBy: { id: "desc" }
18
24
  },
19
- {
20
- name: "sessionList",
21
- fields: ["id", "archived", { name: "fooList", fields: ["id", "uuid"] }],
22
- args: {
23
- $where: { archived: false },
24
- $orderBy: { id: "desc" }
25
- }
26
- },
27
- {
28
- name: "usrList",
29
- fields: ["firstName", "lastName", "password"],
30
- args: {
31
- $where: { valid: false, archived: false },
32
- $orderBy: { id: "desc" }
33
- }
25
+ usrList: {
26
+ $fields: { firstName: true, lastName: true, password: true },
27
+ $where: { valid: false, archived: false },
28
+ $orderBy: { id: "desc" }
34
29
  }
35
- ];
30
+ };
36
31
  (0, _1.traverseFieldArgs)(fields, addWhereValidTrue_1.addWhereValidTrue);
37
- strict_1.default.deepEqual(fields, [
38
- "id",
39
- "uuid",
40
- {
41
- name: "business",
42
- fields: ["id", "uuid", "name"],
43
- args: { $where: { valid: true } }
32
+ strict_1.default.deepEqual(fields, {
33
+ id: true,
34
+ uuid: true,
35
+ business: {
36
+ $fields: { id: true, uuid: true, name: true },
37
+ $where: { valid: true }
44
38
  },
45
- {
46
- name: "sessionList",
47
- fields: [
48
- "id",
49
- "archived",
50
- {
51
- name: "fooList",
52
- fields: ["id", "uuid"],
53
- args: { $where: { valid: true } }
54
- }
55
- ],
56
- args: {
57
- $where: { valid: true, archived: false },
58
- $orderBy: { id: "desc" }
59
- }
39
+ sessionList: {
40
+ $fields: {
41
+ id: true,
42
+ archived: true,
43
+ fooList: { $fields: { id: true, uuid: true }, $where: { valid: true } }
44
+ },
45
+ $where: { valid: true, archived: false },
46
+ $orderBy: { id: "desc" }
60
47
  },
61
- {
62
- name: "usrList",
63
- fields: ["firstName", "lastName", "password"],
64
- args: {
65
- // Should not be overwritten
66
- $where: { valid: false, archived: false },
67
- $orderBy: { id: "desc" }
68
- }
48
+ usrList: {
49
+ $fields: { firstName: true, lastName: true, password: true },
50
+ // Should not be overwritten
51
+ $where: { valid: false, archived: false },
52
+ $orderBy: { id: "desc" }
69
53
  }
70
- ]);
54
+ });
71
55
  });
72
56
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@technicity/data-service-generator",
3
- "version": "0.13.26",
3
+ "version": "0.14.0",
4
4
  "main": "./dist/index.js",
5
5
  "files": [
6
6
  "dist"
package/dist/ksql.d.ts DELETED
@@ -1,15 +0,0 @@
1
- declare type THeaders = {
2
- [k: string]: any;
3
- };
4
- export declare class KSQL {
5
- hostname: string;
6
- port: number;
7
- headers?: THeaders;
8
- constructor(options: {
9
- hostname: string;
10
- port: number;
11
- headers?: THeaders;
12
- });
13
- streamQuery(s: string): Promise<any[]>;
14
- }
15
- export {};
package/dist/ksql.js DELETED
@@ -1,78 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || function (mod) {
19
- if (mod && mod.__esModule) return mod;
20
- var result = {};
21
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
- __setModuleDefault(result, mod);
23
- return result;
24
- };
25
- Object.defineProperty(exports, "__esModule", { value: true });
26
- exports.KSQL = void 0;
27
- const http2 = __importStar(require("http2"));
28
- class KSQL {
29
- constructor(options) {
30
- this.hostname = options.hostname;
31
- this.port = options.port;
32
- this.headers = options.headers;
33
- }
34
- async streamQuery(s) {
35
- return new Promise((resolve, reject) => {
36
- const reqBody = JSON.stringify({
37
- sql: s,
38
- properties: {
39
- "ksql.streams.auto.offset.reset": "earliest",
40
- "ksql.query.pull.table.scan.enabled": true,
41
- },
42
- });
43
- const client = http2.connect(`https://${this.hostname}:${this.port}`);
44
- const req = client.request({
45
- [http2.constants.HTTP2_HEADER_SCHEME]: "https",
46
- "Content-Type": "application/json",
47
- "Content-Length": reqBody.length,
48
- ":method": "POST",
49
- ":path": `/query-stream`,
50
- ...this.headers,
51
- });
52
- req.setEncoding("utf8");
53
- let columnNames = [];
54
- let rows = [];
55
- req.on("data", (d) => {
56
- const resData = JSON.parse(d);
57
- if (resData.error_code) {
58
- return reject(new Error(resData.message));
59
- }
60
- if (resData.columnNames) {
61
- columnNames = resData.columnNames;
62
- }
63
- else {
64
- let out = {};
65
- resData.forEach((rd, i) => {
66
- out[columnNames[i]] = rd;
67
- });
68
- rows.push(out);
69
- }
70
- });
71
- req.on("close", () => resolve(rows));
72
- req.on("error", (error) => reject(error));
73
- req.write(reqBody);
74
- req.end();
75
- });
76
- }
77
- }
78
- exports.KSQL = KSQL;