@technicity/data-service-generator 0.12.0-next.0 → 0.12.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.
@@ -0,0 +1,11 @@
1
+ import { type IArtifacts } from "./runtime/IRuntime";
2
+ export declare function getFakeData(input: {
3
+ model: string;
4
+ select?: unknown[];
5
+ isList: boolean;
6
+ artifacts: IArtifacts;
7
+ }): {
8
+ [k: string]: unknown;
9
+ } | {
10
+ [k: string]: unknown;
11
+ }[];
@@ -0,0 +1,78 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getFakeData = void 0;
4
+ function getFakeData(input) {
5
+ const { model, select, isList, artifacts } = input;
6
+ const tableMeta = artifacts[model];
7
+ if (tableMeta === void 0) {
8
+ throw new Error(`Model ${model} not found.`);
9
+ }
10
+ const { fields } = tableMeta;
11
+ let data = {};
12
+ if (select == null) {
13
+ data = fields.reduce((acc, x) => {
14
+ if (x.kind === "scalar") {
15
+ acc[x.name] = getValue(x.type);
16
+ return acc;
17
+ }
18
+ else if (x.kind === "enum") {
19
+ acc[x.name] = x.values[0];
20
+ return acc;
21
+ }
22
+ return acc;
23
+ }, data);
24
+ }
25
+ else {
26
+ for (let x of select) {
27
+ if (!(typeof x === "string" || (typeof x === "object" && x != null))) {
28
+ throw new Error(`Invalid select: ${x}`);
29
+ }
30
+ const name = typeof x === "string" ? x : x.name;
31
+ const fieldName = x.as ?? name;
32
+ const field = fields.find((x) => x.name === name);
33
+ if (field == null) {
34
+ throw new Error(`Field not found: ${name}`);
35
+ }
36
+ if (field.kind === "scalar") {
37
+ data[fieldName] = getValue(field.type);
38
+ }
39
+ else if (field.kind === "enum") {
40
+ data[fieldName] = field.values[0];
41
+ }
42
+ else if (field.kind === "object") {
43
+ if (!(typeof x === "object" && x != null)) {
44
+ throw new Error(`Invalid select: ${x}`);
45
+ }
46
+ data[fieldName] = getFakeData({
47
+ model: field.type,
48
+ select: x.fields,
49
+ artifacts,
50
+ isList: field.isList
51
+ });
52
+ }
53
+ else {
54
+ throw new Error(`Unhandled kind: ${field?.kind}`);
55
+ }
56
+ }
57
+ }
58
+ if (isList) {
59
+ return [data];
60
+ }
61
+ return data;
62
+ }
63
+ exports.getFakeData = getFakeData;
64
+ function getValue(type) {
65
+ if (type === "boolean") {
66
+ return true;
67
+ }
68
+ if (type === "number") {
69
+ return 54.9434;
70
+ }
71
+ if (type === "integer") {
72
+ return 4;
73
+ }
74
+ if (type === "string") {
75
+ return "foo";
76
+ }
77
+ throw new Error(`Unhandled type: ${type}`);
78
+ }
@@ -0,0 +1 @@
1
+ export declare function getIsList(operation: string): boolean;
@@ -0,0 +1,7 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getIsList = void 0;
4
+ function getIsList(operation) {
5
+ return operation.endsWith("Paginated") || operation.endsWith("Many");
6
+ }
7
+ exports.getIsList = getIsList;
package/dist/index.d.ts CHANGED
@@ -2,3 +2,5 @@ export { generate } from "./generation/generate";
2
2
  export { SDKNotFoundError } from "./runtime/lib/SDKNotFoundError";
3
3
  export { SDKBadWhereError } from "./runtime/lib/SDKBadWhereError";
4
4
  export { traverseFieldArgs } from "./traverseFieldArgs";
5
+ export { getFakeData } from "./getFakeData";
6
+ export { getIsList } from "./getIsList";
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.traverseFieldArgs = exports.SDKBadWhereError = exports.SDKNotFoundError = exports.generate = void 0;
3
+ exports.getIsList = exports.getFakeData = exports.traverseFieldArgs = exports.SDKBadWhereError = exports.SDKNotFoundError = exports.generate = void 0;
4
4
  var generate_1 = require("./generation/generate");
5
5
  Object.defineProperty(exports, "generate", { enumerable: true, get: function () { return generate_1.generate; } });
6
6
  var SDKNotFoundError_1 = require("./runtime/lib/SDKNotFoundError");
@@ -9,3 +9,7 @@ var SDKBadWhereError_1 = require("./runtime/lib/SDKBadWhereError");
9
9
  Object.defineProperty(exports, "SDKBadWhereError", { enumerable: true, get: function () { return SDKBadWhereError_1.SDKBadWhereError; } });
10
10
  var traverseFieldArgs_1 = require("./traverseFieldArgs");
11
11
  Object.defineProperty(exports, "traverseFieldArgs", { enumerable: true, get: function () { return traverseFieldArgs_1.traverseFieldArgs; } });
12
+ var getFakeData_1 = require("./getFakeData");
13
+ Object.defineProperty(exports, "getFakeData", { enumerable: true, get: function () { return getFakeData_1.getFakeData; } });
14
+ var getIsList_1 = require("./getIsList");
15
+ Object.defineProperty(exports, "getIsList", { enumerable: true, get: function () { return getIsList_1.getIsList; } });
@@ -1,11 +1,20 @@
1
- import { RedisClientType } from 'redis';
2
- import { TResolveParams } from './IRuntime';
1
+ import Redis, { Cluster } from "ioredis";
2
+ import { TResolveParams } from "./IRuntime";
3
+ import Stats from "./Stats";
4
+ export declare type RedisConfig = {
5
+ host: string;
6
+ port: number;
7
+ tls?: boolean;
8
+ db?: number;
9
+ socketTimeout?: number;
10
+ clusterMode?: boolean;
11
+ };
3
12
  declare class Cache {
4
- protected logs?: boolean | undefined;
5
- client: RedisClientType;
13
+ client: Redis | Cluster;
6
14
  waiting?: Set<() => void> | undefined;
7
- constructor(url: string, logs?: boolean | undefined);
8
- log(message: string): void;
15
+ stats?: Stats;
16
+ constructor(redisConfig: RedisConfig, debug?: string[]);
17
+ debug(message: string): void;
9
18
  pending(): Promise<void>;
10
19
  from(input: TResolveParams): Promise<{
11
20
  request: string;
@@ -14,5 +23,6 @@ declare class Cache {
14
23
  insert(key: string, payload: any): Promise<void>;
15
24
  read(key: string): Promise<any>;
16
25
  purge(...uuids: string[]): Promise<void>;
26
+ shutdown(): Promise<void>;
17
27
  }
18
28
  export default Cache;
@@ -1,36 +1,85 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  const crypto_1 = require("crypto");
4
- const redis_1 = require("redis");
4
+ const ioredis_1 = require("ioredis");
5
+ const loglevel_1 = require("loglevel");
5
6
  const utility_1 = require("./lib/utility");
7
+ const Stats_1 = require("./Stats");
6
8
  class Cache {
7
- constructor(url, logs) {
8
- this.logs = logs;
9
+ constructor(redisConfig, debug) {
9
10
  this.waiting = new Set();
10
- this.client = (0, redis_1.createClient)({ url: `redis://${url}` });
11
- this.client.connect();
12
- this.client.on("connect", () => {
11
+ if (debug?.includes("Cache")) {
12
+ loglevel_1.default.setLevel("DEBUG");
13
+ }
14
+ const { host, port } = redisConfig;
15
+ const tls = redisConfig.tls ? true : false;
16
+ const clusterMode = redisConfig.clusterMode ? true : false;
17
+ const db = redisConfig.db == null ? 0 : redisConfig.db;
18
+ const socketTimeout = redisConfig.socketTimeout == null ? 50000 : redisConfig.socketTimeout;
19
+ let client = undefined;
20
+ if (clusterMode) {
21
+ client = new ioredis_1.default.Cluster([
22
+ {
23
+ host,
24
+ port
25
+ }
26
+ ], {
27
+ dnsLookup: (address, callback) => callback(null, address),
28
+ redisOptions: {
29
+ tls: tls ? {} : undefined,
30
+ lazyConnect: true,
31
+ commandTimeout: socketTimeout
32
+ }
33
+ });
34
+ }
35
+ else {
36
+ client = new ioredis_1.default({
37
+ host,
38
+ port,
39
+ db,
40
+ lazyConnect: true,
41
+ tls: tls ? {} : undefined
42
+ });
43
+ }
44
+ this.client = client;
45
+ // call connect() if not already connected or in the process of connecting
46
+ if (client.status !== "connect" &&
47
+ client.status !== "connecting" &&
48
+ client.status !== "reconnecting") {
49
+ client.connect();
50
+ }
51
+ else {
52
+ loglevel_1.default.info("DB SDK client status is currently: " + client.status);
53
+ }
54
+ client.on("connect", () => {
55
+ loglevel_1.default.info(`DB SDK connected to redis server at ${host}:${port}`);
13
56
  if (this.waiting)
14
- this.waiting.forEach(x => x());
57
+ this.waiting.forEach((x) => x());
15
58
  this.waiting = undefined;
16
59
  });
60
+ client.on("error", (err) => {
61
+ loglevel_1.default.error("ERROR: redis client");
62
+ loglevel_1.default.error(err);
63
+ });
64
+ if (debug?.includes("Stats"))
65
+ this.stats = new Stats_1.default(client);
17
66
  }
18
- log(message) {
19
- if (this.logs)
20
- console.log(message);
67
+ debug(message) {
68
+ loglevel_1.default.debug(`\n-- CACHE: ${message}\n`);
21
69
  }
22
70
  async pending() {
23
71
  if (this.waiting)
24
- return new Promise(res => this.waiting.add(res));
72
+ return new Promise((res) => this.waiting.add(res));
25
73
  }
26
74
  async from(input) {
27
75
  let { action, args, fields, resource } = input;
28
76
  const request = JSON.stringify({
29
- action, resource, args, fields
77
+ action,
78
+ resource,
79
+ args,
80
+ fields
30
81
  });
31
- const key = (0, crypto_1.createHash)('sha256')
32
- .update(request)
33
- .digest('hex');
82
+ const key = (0, crypto_1.createHash)("sha256").update(request).digest("hex");
34
83
  const cached = await this.read(key);
35
84
  return {
36
85
  request: key,
@@ -42,42 +91,39 @@ class Cache {
42
91
  const json = JSON.stringify(payload);
43
92
  const regex = /"uuid":"(.+?)"/g;
44
93
  const pending = [];
45
- for (let result; result = regex.exec(json);) {
94
+ for (let result; (result = regex.exec(json));) {
46
95
  const uuid = result[1];
47
96
  if (!uuid)
48
97
  continue;
49
- pending.push(redis.sAdd(`deps:${uuid}`, [key]), redis.sAdd(`cached:${key}`, [uuid]));
98
+ pending.push(redis.sadd(`deps:${uuid}`, [key]), redis.sadd(`cached:${key}`, [uuid]));
50
99
  }
51
100
  if (!pending.length)
52
101
  return;
53
- this.log(`Cache insert: ${key.substring(0, 6)}`);
54
- await Promise.all([
55
- redis.set(`cache:${key}`, json),
56
- ...pending
57
- ]);
102
+ this.debug(`insert: ${key.substring(0, 6)}`);
103
+ await Promise.all([redis.set(`cache:${key}`, json), ...pending]);
58
104
  }
59
105
  async read(key) {
60
106
  await this.pending();
61
107
  const data = await this.client.get(`cache:${key}`);
62
108
  const shorthand = key.substring(0, 6);
63
109
  if (data) {
64
- this.log(`Cache hit: ${shorthand}`);
110
+ this.debug(`hit: ${shorthand}`);
65
111
  return JSON.parse(data);
66
112
  }
67
113
  else {
68
- this.log(`Cache miss: ${shorthand}`);
114
+ this.debug(`miss: ${shorthand}`);
69
115
  return undefined;
70
116
  }
71
117
  }
72
118
  async purge(...uuids) {
73
119
  const redis = this.client;
74
- await (0, utility_1.mapAsync)(uuids, uuid => {
75
- const getDependancies = redis.sMembers(`deps:${uuid}`);
120
+ await (0, utility_1.mapAsync)(uuids, (uuid) => {
121
+ const getDependancies = redis.smembers(`deps:${uuid}`);
76
122
  return [
77
- (0, utility_1.mapAsync)(getDependancies, key => {
78
- const getDependants = redis.sMembers(`cached:${key}`);
123
+ (0, utility_1.mapAsync)(getDependancies, (key) => {
124
+ const getDependants = redis.smembers(`cached:${key}`);
79
125
  return [
80
- (0, utility_1.mapAsync)(getDependants, uuid => (redis.sRem(`deps:${uuid}`, [key]))),
126
+ (0, utility_1.mapAsync)(getDependants, (uuid) => redis.srem(`deps:${uuid}`, [key])),
81
127
  redis.del(`cache:${key}`),
82
128
  redis.del(`cached:${key}`)
83
129
  ];
@@ -86,5 +132,8 @@ class Cache {
86
132
  ];
87
133
  });
88
134
  }
135
+ async shutdown() {
136
+ await this.client.disconnect();
137
+ }
89
138
  }
90
139
  exports.default = Cache;
@@ -5,16 +5,22 @@ export interface IRuntime {
5
5
  $whereNeedsProcessing(where: any): boolean;
6
6
  $prepareWhere(artifacts: IArtifacts, table: string, data: any): Promise<any>;
7
7
  $shutdown(): Promise<void>;
8
+ $startTransaction(input?: {
9
+ isolationLevel?: "READ UNCOMMITTED" | "READ COMMITTED" | "REPEATABLE READ" | "SERIALIZABLE";
10
+ }): Promise<TBeginTransactionResult>;
8
11
  }
12
+ export declare type TAction = "findUnique" | "findMany" | "findManyPaginated" | "create" | "update" | "updateMany" | "delete" | "deleteMany";
9
13
  export declare type TResolveParams = {
10
14
  resource: string;
11
- action: "findUnique" | "findMany" | "findManyPaginated" | "create" | "update" | "updateMany" | "delete" | "deleteMany";
15
+ action: TAction;
12
16
  args?: IArgs | undefined;
13
17
  data?: any;
14
18
  artifacts: IArtifacts;
15
19
  fields?: IField[] | undefined;
16
20
  context?: TContext | undefined;
17
21
  skipCache?: boolean;
22
+ dbCall?: TDbCall;
23
+ nullability?: unknown;
18
24
  };
19
25
  export declare type TContext = {
20
26
  [k: string]: any;
@@ -23,10 +29,12 @@ export declare type TMiddleware = (params: TResolveParams, next: (params: TResol
23
29
  export declare type IDialect = "mysql" | "mssql" | "ksql";
24
30
  export declare type TDbCall = (q: string) => Promise<any>;
25
31
  export declare type TFormatQuery = (q: string, values: any[]) => string;
26
- export declare type TBeginTransaction = () => Promise<{
32
+ export declare type TBeginTransaction = () => Promise<TBeginTransactionResult>;
33
+ declare type TBeginTransactionResult = {
27
34
  dbCall: (q: string) => Promise<any>;
28
35
  commit: () => Promise<void>;
29
- }>;
36
+ rollback: () => Promise<void>;
37
+ };
30
38
  export declare type ISupplementClientOpts = boolean;
31
39
  export declare type IOrderBy = {
32
40
  column: string;
@@ -153,6 +161,25 @@ export declare type IArtifacts = {
153
161
  [k: string]: boolean;
154
162
  };
155
163
  dateTimeFieldsCount: number;
164
+ fields: TField[];
156
165
  };
157
166
  };
167
+ export declare type TFieldType = "string" | "boolean" | "number" | "integer";
168
+ export declare type TField = {
169
+ kind: "scalar";
170
+ type: TFieldType;
171
+ name: string;
172
+ nullable: boolean;
173
+ hasDefaultValue: boolean;
174
+ } | {
175
+ kind: "enum";
176
+ values: unknown[];
177
+ name: string;
178
+ nullable: boolean;
179
+ } | {
180
+ kind: "object";
181
+ type: string;
182
+ name: string;
183
+ isList: boolean;
184
+ };
158
185
  export {};
@@ -15,5 +15,12 @@ export declare class RuntimeKSQL implements IRuntime {
15
15
  $whereNeedsProcessing(where: any): boolean;
16
16
  $prepareWhere(artifacts: IArtifacts, table: string, data: any): Promise<{}>;
17
17
  $shutdown(): Promise<void>;
18
+ $startTransaction(input?: {
19
+ isolationLevel?: "READ UNCOMMITTED" | "READ COMMITTED" | "REPEATABLE READ" | "SERIALIZABLE";
20
+ }): Promise<{
21
+ dbCall: (q: string) => Promise<string>;
22
+ commit: () => Promise<void>;
23
+ rollback: () => Promise<void>;
24
+ }>;
18
25
  }
19
26
  export {};
@@ -60,6 +60,14 @@ class RuntimeKSQL {
60
60
  async $shutdown() {
61
61
  // Nothing to do here, I think
62
62
  }
63
+ async $startTransaction(input) {
64
+ throw new Error("Not implemented.");
65
+ return {
66
+ dbCall: async (q) => "",
67
+ commit: async () => { },
68
+ rollback: async () => { }
69
+ };
70
+ }
63
71
  }
64
72
  exports.RuntimeKSQL = RuntimeKSQL;
65
73
  _RuntimeKSQL_ksql = new WeakMap(), _RuntimeKSQL_middlewareHandler = new WeakMap(), _RuntimeKSQL_dbCall = new WeakMap(), _RuntimeKSQL_formatQuery = new WeakMap(), _RuntimeKSQL_getBaseTableName = new WeakMap(), _RuntimeKSQL_getMaterializedViewName = new WeakMap(), _RuntimeKSQL_doNotUseMaterializedViews = new WeakMap();
@@ -151,8 +159,7 @@ async function _getData(input, grabMany, dbCall, formatQuery, getBaseTableName,
151
159
  let where = undefined;
152
160
  if (args?.$where != null) {
153
161
  let argsMapped = args;
154
- if (typeof argsMapped.$where === "object" &&
155
- argsMapped.$where[table] != null) {
162
+ if (typeof argsMapped.$where === "object" && argsMapped.$where[table] != null) {
156
163
  argsMapped = _.cloneDeep(argsMapped);
157
164
  argsMapped.$where = argsMapped.$where[table];
158
165
  }
@@ -160,7 +167,7 @@ async function _getData(input, grabMany, dbCall, formatQuery, getBaseTableName,
160
167
  where: argsMapped.$where,
161
168
  table: escapeId(getTableName(table)),
162
169
  dialect: "mysql",
163
- args: argsMapped,
170
+ args: argsMapped
164
171
  });
165
172
  if (whereResult) {
166
173
  where = whereResult;
@@ -288,10 +295,10 @@ async function resolveDependentFields(table, parentData, mappedFields, relationF
288
295
  mappedField.name,
289
296
  getBaseTableName(mappedField.referencedTable),
290
297
  mappedField.referencedKey,
291
- parentData?.[mappedField.foreignKey],
298
+ parentData?.[mappedField.foreignKey]
292
299
  ]);
293
300
  return dbCall(s).then((xs) => ({
294
- [x]: xs?.[0]?.[mappedField.name] ?? null,
301
+ [x]: xs?.[0]?.[mappedField.name] ?? null
295
302
  }));
296
303
  }))
297
304
  .concat(relationFields.map((x) => {
@@ -316,8 +323,8 @@ async function resolveDependentFields(table, parentData, mappedFields, relationF
316
323
  whereJunction = {
317
324
  $and: [
318
325
  { [relationField.relations[0].foreignKey]: junctionKeyValue },
319
- whereJunction,
320
- ],
326
+ whereJunction
327
+ ]
321
328
  };
322
329
  const key = relationField.relations[1].foreignKey;
323
330
  const s = formatQuery(`SELECT ?? FROM ?? WHERE ${(0, stringifyWhere_1.stringifyWhere)({
@@ -325,20 +332,20 @@ async function resolveDependentFields(table, parentData, mappedFields, relationF
325
332
  table: escapeId(getBaseTableName(relationField.junctionTable)),
326
333
  dialect: "mysql",
327
334
  // Since we're paginating, empty is fine
328
- args: {},
335
+ args: {}
329
336
  })};`, [key, getBaseTableName(relationField.junctionTable)]);
330
337
  return dbCall(s)
331
338
  .then((xs) => xs.map((x) => x?.[key]))
332
339
  .then((keys) => {
333
340
  const whereDest = {
334
- [relationField.relations[1].referencedKey]: { $in: keys },
341
+ [relationField.relations[1].referencedKey]: { $in: keys }
335
342
  };
336
343
  const argsMapped = x.args == null ? {} : _.cloneDeep(x.args);
337
344
  if (typeof argsMapped?.$where === "object" &&
338
345
  argsMapped.$where != null &&
339
346
  argsMapped.$where[relationField.table] != null) {
340
347
  argsMapped.$where = {
341
- $and: [whereDest, argsMapped.$where[relationField.table]],
348
+ $and: [whereDest, argsMapped.$where[relationField.table]]
342
349
  };
343
350
  }
344
351
  else if (argsMapped.$where != null) {
@@ -352,7 +359,7 @@ async function resolveDependentFields(table, parentData, mappedFields, relationF
352
359
  args: argsMapped,
353
360
  fields: x.fields,
354
361
  artifacts,
355
- action: relationField.grabMany ? "findMany" : "findUnique",
362
+ action: relationField.grabMany ? "findMany" : "findUnique"
356
363
  }, relationField.grabMany, dbCall, formatQuery, getBaseTableName, getMaterializedViewName, doNotUseMaterializedViews).then((xx) => ({ [x.as ?? x.name]: xx }));
357
364
  });
358
365
  }
@@ -375,7 +382,7 @@ async function resolveDependentFields(table, parentData, mappedFields, relationF
375
382
  args: argsMapped,
376
383
  fields: x.fields,
377
384
  artifacts,
378
- action: relationField.grabMany ? "findMany" : "findUnique",
385
+ action: relationField.grabMany ? "findMany" : "findUnique"
379
386
  }, relationField.grabMany, dbCall, formatQuery, getBaseTableName, getMaterializedViewName, doNotUseMaterializedViews).then((xx) => ({ [x.as ?? x.name]: xx }));
380
387
  }
381
388
  throw new Error(`Invalid relationField.type`);
@@ -396,7 +403,7 @@ function paginate(data, args, primaryKey, action) {
396
403
  data = data.slice(offset, offset + limit);
397
404
  return {
398
405
  results: data,
399
- paginationInfo: { totalCount },
406
+ paginationInfo: { totalCount }
400
407
  };
401
408
  }
402
409
  if (typeof args?.$paginate?.first === "number" ||
@@ -427,8 +434,8 @@ function paginate(data, args, primaryKey, action) {
427
434
  ...connection.pageInfo,
428
435
  startCursor,
429
436
  endCursor,
430
- totalCount,
431
- },
437
+ totalCount
438
+ }
432
439
  };
433
440
  }
434
441
  }
@@ -13,7 +13,13 @@ export declare class RuntimeMSSQL implements IRuntime {
13
13
  $whereNeedsProcessing(where: any): boolean;
14
14
  $prepareWhere(artifacts: IArtifacts, table: string, data: any): Promise<{}>;
15
15
  $shutdown(): Promise<void>;
16
+ $startTransaction(input?: {
17
+ isolationLevel?: "READ UNCOMMITTED" | "READ COMMITTED" | "REPEATABLE READ" | "SERIALIZABLE";
18
+ }): Promise<{
19
+ commit: () => Promise<void>;
20
+ rollback: () => Promise<void>;
21
+ dbCall: (q: string) => Promise<any>;
22
+ }>;
16
23
  private dbCall;
17
24
  private formatQuery;
18
- private beginTransaction;
19
25
  }
@@ -27,7 +27,7 @@ class RuntimeMSSQL {
27
27
  __classPrivateFieldSet(this, _RuntimeMSSQL_middlewareHandler, new shared_1.MiddlewareHandler(), "f");
28
28
  }
29
29
  async resolve(input) {
30
- return (0, shared_1.resolve)(input, this.dbCall.bind(this), this.formatQuery.bind(this), this.beginTransaction.bind(this), __classPrivateFieldGet(this, _RuntimeMSSQL_dialect, "f"), __classPrivateFieldGet(this, _RuntimeMSSQL_middlewareHandler, "f"), input.context ?? {});
30
+ return (0, shared_1.resolve)(input, input.dbCall ?? this.dbCall.bind(this), this.formatQuery.bind(this), this.$startTransaction.bind(this), __classPrivateFieldGet(this, _RuntimeMSSQL_dialect, "f"), __classPrivateFieldGet(this, _RuntimeMSSQL_middlewareHandler, "f"), input.context ?? {});
31
31
  }
32
32
  async $queryRaw(sql, values) {
33
33
  return this.dbCall(this.formatQuery(sql, values ?? []));
@@ -44,15 +44,15 @@ class RuntimeMSSQL {
44
44
  async $shutdown() {
45
45
  await __classPrivateFieldGet(this, _RuntimeMSSQL_mssqlClient, "f").closePool();
46
46
  }
47
+ async $startTransaction(input) {
48
+ return __classPrivateFieldGet(this, _RuntimeMSSQL_mssqlClient, "f").beginTransaction(input?.isolationLevel);
49
+ }
47
50
  async dbCall(q) {
48
51
  return __classPrivateFieldGet(this, _RuntimeMSSQL_mssqlClient, "f").dbCall(q);
49
52
  }
50
53
  formatQuery(q, values) {
51
54
  return __classPrivateFieldGet(this, _RuntimeMSSQL_mssqlClient, "f").formatQuery(q, values);
52
55
  }
53
- beginTransaction() {
54
- return __classPrivateFieldGet(this, _RuntimeMSSQL_mssqlClient, "f").beginTransaction();
55
- }
56
56
  }
57
57
  exports.RuntimeMSSQL = RuntimeMSSQL;
58
58
  _RuntimeMSSQL_dialect = new WeakMap(), _RuntimeMSSQL_mssqlClient = new WeakMap(), _RuntimeMSSQL_middlewareHandler = new WeakMap();
@@ -1,3 +1,4 @@
1
+ import { RedisConfig } from "./Cache";
1
2
  import type { IRuntime, TMiddleware, TResolveParams, IArtifacts, ISupplementClientOpts } from "./IRuntime";
2
3
  export declare class RuntimeMySQL implements IRuntime {
3
4
  #private;
@@ -5,7 +6,7 @@ export declare class RuntimeMySQL implements IRuntime {
5
6
  [k: string]: any;
6
7
  }, otherOpts: {
7
8
  supplementClientOpts?: ISupplementClientOpts;
8
- redisHost?: string;
9
+ redis?: RedisConfig;
9
10
  }, artifacts: IArtifacts);
10
11
  resolve(input: TResolveParams): Promise<any>;
11
12
  $queryRaw(sql: string, values?: any[]): Promise<any>;
@@ -13,7 +14,9 @@ export declare class RuntimeMySQL implements IRuntime {
13
14
  $whereNeedsProcessing(where: any): boolean;
14
15
  $prepareWhere(artifacts: IArtifacts, table: string, data: any): Promise<{}>;
15
16
  $shutdown(): Promise<void>;
17
+ $startTransaction(input?: {
18
+ isolationLevel?: "READ UNCOMMITTED" | "READ COMMITTED" | "REPEATABLE READ" | "SERIALIZABLE";
19
+ }): Promise<any>;
16
20
  private dbCall;
17
21
  private formatQuery;
18
- private beginTransaction;
19
22
  }
@@ -17,6 +17,8 @@ const SqlString = require("sqlstring");
17
17
  const Cache_1 = require("./Cache");
18
18
  const MySQL_1 = require("./lib/MySQL");
19
19
  const shared_1 = require("./lib/shared");
20
+ const loglevel_1 = require("loglevel");
21
+ loglevel_1.default.setDefaultLevel("INFO");
20
22
  class RuntimeMySQL {
21
23
  constructor(clientOpts, otherOpts, artifacts) {
22
24
  _RuntimeMySQL_dialect.set(this, "mysql");
@@ -24,9 +26,8 @@ class RuntimeMySQL {
24
26
  _RuntimeMySQL_clientCache.set(this, void 0);
25
27
  _RuntimeMySQL_middlewareHandler.set(this, void 0);
26
28
  __classPrivateFieldSet(this, _RuntimeMySQL_middlewareHandler, new shared_1.MiddlewareHandler(), "f");
27
- const debugCache = clientOpts?.debug?.includes("Cache");
28
- if (otherOpts.redisHost)
29
- __classPrivateFieldSet(this, _RuntimeMySQL_clientCache, new Cache_1.default(otherOpts.redisHost, debugCache), "f");
29
+ if (otherOpts.redis)
30
+ __classPrivateFieldSet(this, _RuntimeMySQL_clientCache, new Cache_1.default(otherOpts.redis, clientOpts?.debug), "f");
30
31
  if (otherOpts.supplementClientOpts) {
31
32
  clientOpts = {
32
33
  supportBigNumbers: true,
@@ -49,7 +50,7 @@ class RuntimeMySQL {
49
50
  }
50
51
  return next();
51
52
  },
52
- ...clientOpts,
53
+ ...clientOpts
53
54
  };
54
55
  }
55
56
  else {
@@ -63,13 +64,13 @@ class RuntimeMySQL {
63
64
  }
64
65
  return next();
65
66
  },
66
- ...clientOpts,
67
+ ...clientOpts
67
68
  };
68
69
  }
69
70
  __classPrivateFieldSet(this, _RuntimeMySQL_mysqlClient, new MySQL_1.MySQL(clientOpts), "f");
70
71
  }
71
72
  async resolve(input) {
72
- return (0, shared_1.resolve)(input, this.dbCall.bind(this), this.formatQuery.bind(this), this.beginTransaction.bind(this), __classPrivateFieldGet(this, _RuntimeMySQL_dialect, "f"), __classPrivateFieldGet(this, _RuntimeMySQL_middlewareHandler, "f"), input.context ?? {}, __classPrivateFieldGet(this, _RuntimeMySQL_clientCache, "f"));
73
+ return (0, shared_1.resolve)(input, input.dbCall ?? this.dbCall.bind(this), this.formatQuery.bind(this), this.$startTransaction.bind(this), __classPrivateFieldGet(this, _RuntimeMySQL_dialect, "f"), __classPrivateFieldGet(this, _RuntimeMySQL_middlewareHandler, "f"), input.context ?? {}, __classPrivateFieldGet(this, _RuntimeMySQL_clientCache, "f"));
73
74
  }
74
75
  async $queryRaw(sql, values) {
75
76
  return this.dbCall(this.formatQuery(sql, values ?? []));
@@ -84,17 +85,20 @@ class RuntimeMySQL {
84
85
  return (0, shared_1._prepareWhere)(artifacts, table, data, this.dbCall.bind(this), this.formatQuery.bind(this));
85
86
  }
86
87
  async $shutdown() {
88
+ if (__classPrivateFieldGet(this, _RuntimeMySQL_clientCache, "f")) {
89
+ await __classPrivateFieldGet(this, _RuntimeMySQL_clientCache, "f").shutdown();
90
+ }
87
91
  await __classPrivateFieldGet(this, _RuntimeMySQL_mysqlClient, "f").endPool();
88
92
  }
93
+ async $startTransaction(input) {
94
+ return __classPrivateFieldGet(this, _RuntimeMySQL_mysqlClient, "f").beginTransaction(input?.isolationLevel);
95
+ }
89
96
  dbCall(q) {
90
97
  return __classPrivateFieldGet(this, _RuntimeMySQL_mysqlClient, "f").query(q);
91
98
  }
92
99
  formatQuery(q, values) {
93
100
  return SqlString.format(q, values);
94
101
  }
95
- beginTransaction() {
96
- return __classPrivateFieldGet(this, _RuntimeMySQL_mysqlClient, "f").beginTransaction();
97
- }
98
102
  }
99
103
  exports.RuntimeMySQL = RuntimeMySQL;
100
104
  _RuntimeMySQL_dialect = new WeakMap(), _RuntimeMySQL_mysqlClient = new WeakMap(), _RuntimeMySQL_clientCache = new WeakMap(), _RuntimeMySQL_middlewareHandler = new WeakMap();