@snowtop/ent 0.1.0-alpha → 0.1.0-alpha6

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/schema/field.js CHANGED
@@ -40,19 +40,25 @@ class UUIDField extends BaseField {
40
40
  super();
41
41
  this.options = options;
42
42
  this.type = { dbType: schema_1.DBType.UUID };
43
- const polymorphic = options.polymorphic;
43
+ if (options?.fieldEdge?.enforceSchema &&
44
+ !options.fieldEdge.getLoaderInfoFromSchema) {
45
+ throw new Error(`cannot enforceSchema if getLoaderInfoFromSchema wasn't passed in`);
46
+ }
47
+ }
48
+ getDerivedFields(fieldName) {
49
+ const polymorphic = this.options?.polymorphic;
44
50
  if (polymorphic) {
45
51
  let name = "";
46
- if (options.name.endsWith("_id")) {
47
- let idx = options.name.indexOf("_id");
48
- name = options.name.substring(0, idx) + "_type";
52
+ if (fieldName.endsWith("_id")) {
53
+ let idx = fieldName.indexOf("_id");
54
+ name = fieldName.substring(0, idx) + "_type";
49
55
  }
50
- else if (options.name.endsWith("ID")) {
51
- let idx = options.name.indexOf("ID");
52
- name = options.name.substring(0, idx) + "Type";
56
+ else if (fieldName.endsWith("ID")) {
57
+ let idx = fieldName.indexOf("ID");
58
+ name = fieldName.substring(0, idx) + "Type";
53
59
  }
54
60
  else {
55
- throw new Error(`unsupported id polymorhpic type ${options.name}`);
61
+ throw new Error(`unsupported id polymorhpic type ${fieldName}`);
56
62
  }
57
63
  // polymorphic field automatically hidden from GraphQL
58
64
  // can be made visible with custom fields if user wants to change this behavior
@@ -60,38 +66,33 @@ class UUIDField extends BaseField {
60
66
  // intentionally not made private as it doesn't seem like it needs to be hidden
61
67
  if (typeof polymorphic === "object" && polymorphic.types) {
62
68
  // an enum with types validated here
63
- this.derivedFields = [
64
- EnumType({
65
- name,
69
+ return {
70
+ [name]: EnumType({
66
71
  values: polymorphic.types,
67
72
  hideFromGraphQL: true,
68
73
  derivedWhenEmbedded: true,
69
- nullable: options.nullable,
74
+ nullable: this.options?.nullable,
70
75
  }),
71
- ];
76
+ };
72
77
  }
73
78
  else {
74
79
  // just a string field...
75
- this.derivedFields = [
76
- StringType({
77
- name,
80
+ return {
81
+ [name]: StringType({
78
82
  hideFromGraphQL: true,
79
83
  derivedWhenEmbedded: true,
80
- nullable: options.nullable,
84
+ nullable: this.options?.nullable,
81
85
  }),
82
- ];
86
+ };
83
87
  }
84
88
  }
85
- if (options.fieldEdge?.enforceSchema &&
86
- !options.fieldEdge.getLoaderInfoFromSchema) {
87
- throw new Error(`cannot enforceSchema if getLoaderInfoFromSchema wasn't passed in`);
88
- }
89
+ return {};
89
90
  }
90
91
  isBuilder(val) {
91
92
  return val.placeholderID !== undefined;
92
93
  }
93
94
  async valid(val) {
94
- if (!this.options.fieldEdge?.enforceSchema) {
95
+ if (!this.options?.fieldEdge?.enforceSchema) {
95
96
  return true;
96
97
  }
97
98
  const getLoaderInfo = this.options.fieldEdge.getLoaderInfoFromSchema;
@@ -119,7 +120,7 @@ class IntegerField extends BaseField {
119
120
  super();
120
121
  this.type = { dbType: schema_1.DBType.Int };
121
122
  this.validators = [];
122
- this.options = { name: "field" };
123
+ this.options = {};
123
124
  // for legacy callers
124
125
  this.handleOptions(options || this.options);
125
126
  }
@@ -206,9 +207,9 @@ class StringField extends BaseField {
206
207
  this.type = { dbType: schema_1.DBType.String };
207
208
  this.validators = [];
208
209
  this.formatters = [];
209
- this.options = { name: "field" };
210
+ this.options = {};
210
211
  // for legacy callers
211
- this.handleOptions(options || { name: "field" });
212
+ this.handleOptions(options || {});
212
213
  }
213
214
  getOptions() {
214
215
  return this.options;
@@ -347,7 +348,7 @@ class TimestampField extends BaseField {
347
348
  }
348
349
  exports.TimestampField = TimestampField;
349
350
  function TimestampType(options) {
350
- let result = new TimestampField(options);
351
+ let result = new TimestampField({ ...options });
351
352
  return Object.assign(result, options);
352
353
  }
353
354
  exports.TimestampType = TimestampType;
@@ -374,7 +375,7 @@ class TimeField extends BaseField {
374
375
  constructor(options) {
375
376
  super();
376
377
  this.type = { dbType: schema_1.DBType.Time };
377
- if (options.withTimezone) {
378
+ if (options?.withTimezone) {
378
379
  this.type = {
379
380
  dbType: schema_1.DBType.Timetz,
380
381
  };
@@ -451,8 +452,8 @@ class EnumField extends BaseField {
451
452
  dbType: options.createEnumType ? schema_1.DBType.Enum : schema_1.DBType.StringEnum,
452
453
  values: options.values,
453
454
  enumMap: options.map,
454
- type: options.tsType || options.name,
455
- graphQLType: options.graphQLType || options.name,
455
+ type: options.tsType,
456
+ graphQLType: options.graphQLType,
456
457
  };
457
458
  if (!options.foreignKey) {
458
459
  if (!options.values && !options.map) {
@@ -596,13 +597,17 @@ class ListField extends BaseField {
596
597
  }
597
598
  return JSON.stringify(val);
598
599
  }
599
- format(val) {
600
+ format(val, nested) {
600
601
  if (!Array.isArray(val)) {
601
602
  throw new Error(`need an array to format`);
602
603
  }
603
604
  const elemDBType = this.type.listElemType.dbType;
604
605
  const jsonType = elemDBType === "JSON" || elemDBType === "JSONB";
605
- const postgres = db_1.default.getDialect() === db_1.Dialect.Postgres;
606
+ // postgres ish doesn't apply when nested
607
+ const postgres = !nested && db_1.default.getDialect() === db_1.Dialect.Postgres;
608
+ if (nested && !this.field.format) {
609
+ return val;
610
+ }
606
611
  if (!postgres && !this.field.format) {
607
612
  return JSON.stringify(val);
608
613
  }
@@ -628,6 +633,10 @@ class ListField extends BaseField {
628
633
  if (postgres) {
629
634
  return postgresRet + "}";
630
635
  }
636
+ // don't JSON.stringify if nested
637
+ if (nested) {
638
+ return ret;
639
+ }
631
640
  return JSON.stringify(ret);
632
641
  }
633
642
  minLen(l) {
package/schema/index.d.ts CHANGED
@@ -1,6 +1,8 @@
1
1
  import Schema from "./schema";
2
2
  export { Schema };
3
- export { Field, AssocEdge, AssocEdgeGroup, InverseAssocEdge, Edge, Pattern, DBType, Type, FieldOptions, SchemaConstructor, SchemaInputType, getFields, ActionOperation, Action, EdgeAction, NoFields, Constraint, Index, ConstraintType, ForeignKeyInfo, requiredField, optionalField, } from "./schema";
3
+ export { Field, AssocEdge, AssocEdgeGroup, InverseAssocEdge, Edge, Pattern, DBType, Type, FieldOptions, SchemaConstructor, SchemaInputType, getFields, ActionOperation, Action, EdgeAction, NoFields, FieldMap, Constraint, Index, ConstraintType, ForeignKeyInfo, requiredField, optionalField, } from "./schema";
4
4
  export { Timestamps, Node, BaseEntSchema, BaseEntSchemaWithTZ, } from "./base_schema";
5
5
  export * from "./field";
6
6
  export * from "./json_field";
7
+ export * from "./struct_field";
8
+ export * from "./union_field";
package/schema/index.js CHANGED
@@ -26,3 +26,5 @@ Object.defineProperty(exports, "BaseEntSchema", { enumerable: true, get: functio
26
26
  Object.defineProperty(exports, "BaseEntSchemaWithTZ", { enumerable: true, get: function () { return base_schema_1.BaseEntSchemaWithTZ; } });
27
27
  __exportStar(require("./field"), exports);
28
28
  __exportStar(require("./json_field"), exports);
29
+ __exportStar(require("./struct_field"), exports);
30
+ __exportStar(require("./union_field"), exports);
@@ -5,13 +5,13 @@ export interface JSONOptions extends FieldOptions {
5
5
  importType?: ImportType;
6
6
  }
7
7
  export declare class JSONField extends BaseField implements Field {
8
- private options;
8
+ private options?;
9
9
  type: Type;
10
- constructor(jsonb: boolean, options: JSONOptions);
10
+ constructor(jsonb: boolean, options?: JSONOptions | undefined);
11
11
  format(val: any): string;
12
12
  valid(val: any): boolean;
13
13
  }
14
- export declare function JSONType(options: JSONOptions): JSONField;
15
- export declare function JSONBType(options: JSONOptions): JSONField;
16
- export declare function JSONBListType(options: JSONOptions): ListField;
17
- export declare function JSONListType(options: JSONOptions): ListField;
14
+ export declare function JSONType(options?: JSONOptions): JSONField;
15
+ export declare function JSONBType(options?: JSONOptions): JSONField;
16
+ export declare function JSONBListType(options?: JSONOptions): ListField;
17
+ export declare function JSONListType(options?: JSONOptions): ListField;
@@ -13,7 +13,7 @@ class JSONField extends field_1.BaseField {
13
13
  if (jsonb) {
14
14
  this.type.dbType = schema_1.DBType.JSONB;
15
15
  }
16
- if (options.importType) {
16
+ if (options?.importType) {
17
17
  this.type.importType = options.importType;
18
18
  }
19
19
  }
@@ -21,7 +21,7 @@ class JSONField extends field_1.BaseField {
21
21
  return JSON.stringify(val);
22
22
  }
23
23
  valid(val) {
24
- if (this.options.validator) {
24
+ if (this.options?.validator) {
25
25
  return this.options.validator(val);
26
26
  }
27
27
  return true;
@@ -1,7 +1,10 @@
1
1
  import { Data, Ent, LoaderInfo } from "../core/base";
2
2
  import { Builder } from "../action/action";
3
+ export declare type FieldMap = {
4
+ [key: string]: Field;
5
+ };
3
6
  export default interface Schema {
4
- fields: Field[];
7
+ fields: FieldMap | Field[];
5
8
  tableName?: string;
6
9
  patterns?: Pattern[];
7
10
  edges?: Edge[];
@@ -57,7 +60,7 @@ export interface AssocEdgeGroup {
57
60
  export declare type Edge = AssocEdge;
58
61
  export interface Pattern {
59
62
  name: string;
60
- fields: Field[];
63
+ fields: FieldMap | Field[];
61
64
  edges?: Edge[];
62
65
  }
63
66
  export declare enum DBType {
@@ -94,6 +97,8 @@ export interface Type {
94
97
  values?: string[];
95
98
  enumMap?: EnumMap;
96
99
  importType?: ImportType;
100
+ subFields?: FieldMap;
101
+ unionFields?: FieldMap;
97
102
  }
98
103
  export interface ForeignKey {
99
104
  schema: string;
@@ -117,7 +122,6 @@ export interface FieldEdge {
117
122
  disableBuilderType?: boolean;
118
123
  }
119
124
  export interface FieldOptions {
120
- name: string;
121
125
  nullable?: boolean;
122
126
  storageKey?: string;
123
127
  serverDefault?: any;
@@ -136,7 +140,8 @@ export interface FieldOptions {
136
140
  defaultValueOnEdit?(builder: Builder<Ent>, input: Data): any;
137
141
  derivedWhenEmbedded?: boolean;
138
142
  polymorphic?: boolean | PolymorphicOptions;
139
- derivedFields?: Field[];
143
+ getDerivedFields?(name: string): FieldMap;
144
+ [x: string]: any;
140
145
  }
141
146
  export interface PolymorphicOptions {
142
147
  types?: string[];
@@ -146,7 +151,7 @@ export interface PolymorphicOptions {
146
151
  export interface Field extends FieldOptions {
147
152
  type: Type;
148
153
  valid?(val: any): Promise<boolean> | boolean;
149
- format?(val: any): any;
154
+ format?(val: any, nested?: boolean): any;
150
155
  logValue(val: any): any;
151
156
  }
152
157
  export interface SchemaConstructor {
package/schema/schema.js CHANGED
@@ -37,12 +37,25 @@ function getFields(value) {
37
37
  schema = new value();
38
38
  }
39
39
  function addFields(fields) {
40
- for (const field of fields) {
41
- const derivedFields = field.derivedFields;
42
- if (derivedFields !== undefined) {
43
- addFields(derivedFields);
40
+ if (Array.isArray(fields)) {
41
+ for (const field of fields) {
42
+ const name = field.name;
43
+ if (!name) {
44
+ throw new Error(`name required`);
45
+ }
46
+ if (field.getDerivedFields !== undefined) {
47
+ addFields(field.getDerivedFields(name));
48
+ }
49
+ m.set(name, field);
44
50
  }
45
- m.set(field.name, field);
51
+ return;
52
+ }
53
+ for (const name in fields) {
54
+ const field = fields[name];
55
+ if (field.getDerivedFields !== undefined) {
56
+ addFields(field.getDerivedFields(name));
57
+ }
58
+ m.set(name, field);
46
59
  }
47
60
  }
48
61
  let m = new Map();
@@ -0,0 +1,17 @@
1
+ import { BaseField, ListField } from "./field";
2
+ import { FieldOptions, Field, Type, FieldMap } from "./schema";
3
+ export interface StructOptions extends FieldOptions {
4
+ tsType: string;
5
+ fields: FieldMap;
6
+ graphQLType?: string;
7
+ jsonNotJSONB?: boolean;
8
+ }
9
+ export declare class StructField extends BaseField implements Field {
10
+ private options;
11
+ type: Type;
12
+ constructor(options: StructOptions);
13
+ format(obj: any, nested?: boolean): string | Object;
14
+ valid(obj: any): Promise<boolean>;
15
+ }
16
+ export declare function StructType(options: StructOptions): StructField & StructOptions;
17
+ export declare function StructListType(options: StructOptions): ListField;
@@ -0,0 +1,102 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.StructListType = exports.StructType = exports.StructField = void 0;
4
+ const field_1 = require("./field");
5
+ const schema_1 = require("./schema");
6
+ const camel_case_1 = require("camel-case");
7
+ class StructField extends field_1.BaseField {
8
+ constructor(options) {
9
+ super();
10
+ this.options = options;
11
+ this.type = {
12
+ dbType: schema_1.DBType.JSONB,
13
+ };
14
+ this.type.subFields = options.fields;
15
+ this.type.type = options.tsType;
16
+ this.type.graphQLType = options.graphQLType || options.tsType;
17
+ if (options.jsonNotJSONB) {
18
+ this.type.dbType = schema_1.DBType.JSON;
19
+ }
20
+ }
21
+ // right now, we store things in the db in lowerCase format
22
+ // this will lead to issues if field changes.
23
+ // TODO: use storageKey and convert back...
24
+ format(obj, nested) {
25
+ if (!(obj instanceof Object)) {
26
+ throw new Error("valid was not called");
27
+ }
28
+ let ret = {};
29
+ for (const k in this.options.fields) {
30
+ // TODO more #510
31
+ let dbKey = (0, camel_case_1.camelCase)(k);
32
+ let val = obj[dbKey];
33
+ // for tests with snake_case
34
+ if (val === undefined && obj[k] !== undefined) {
35
+ val = obj[k];
36
+ dbKey = k;
37
+ }
38
+ if (val === undefined) {
39
+ continue;
40
+ }
41
+ const field = this.options.fields[k];
42
+ if (field.format) {
43
+ // indicate nested so this isn't JSON stringified
44
+ ret[dbKey] = field.format(val, true);
45
+ }
46
+ else {
47
+ ret[dbKey] = val;
48
+ }
49
+ }
50
+ // don't json.stringify if nested
51
+ if (nested) {
52
+ return ret;
53
+ }
54
+ return JSON.stringify(ret);
55
+ }
56
+ async valid(obj) {
57
+ if (!(obj instanceof Object)) {
58
+ return false;
59
+ }
60
+ let promises = [];
61
+ // TODO probably need to support optional fields...
62
+ let valid = true;
63
+ for (const k in this.options.fields) {
64
+ const field = this.options.fields[k];
65
+ // TODO more #510
66
+ let dbKey = (0, camel_case_1.camelCase)(k);
67
+ let val = obj[dbKey];
68
+ // for tests with snake_case
69
+ if (val === undefined && obj[k] !== undefined) {
70
+ val = obj[k];
71
+ dbKey = k;
72
+ }
73
+ if (val === undefined || val === null) {
74
+ // nullable, nothing to do here
75
+ if (field.nullable) {
76
+ continue;
77
+ }
78
+ valid = false;
79
+ break;
80
+ }
81
+ if (!field.valid) {
82
+ continue;
83
+ }
84
+ promises.push(field.valid(val));
85
+ }
86
+ if (!valid) {
87
+ return valid;
88
+ }
89
+ const ret = await Promise.all(promises);
90
+ return ret.every((v) => v);
91
+ }
92
+ }
93
+ exports.StructField = StructField;
94
+ function StructType(options) {
95
+ let result = new StructField(options);
96
+ return Object.assign(result, options);
97
+ }
98
+ exports.StructType = StructType;
99
+ function StructListType(options) {
100
+ return new field_1.ListField(StructType(options), options);
101
+ }
102
+ exports.StructListType = StructListType;
@@ -0,0 +1,23 @@
1
+ import { StructField } from "./struct_field";
2
+ import { FieldOptions, Type } from "./schema";
3
+ import { BaseField, ListField } from "./field";
4
+ export declare type StructMap = {
5
+ [key: string]: StructField;
6
+ };
7
+ export interface UnionOptions extends FieldOptions {
8
+ tsType: string;
9
+ fields: StructMap;
10
+ graphQLType?: string;
11
+ jsonNotJSONB?: boolean;
12
+ }
13
+ export declare class UnionField extends BaseField implements FieldOptions {
14
+ private options;
15
+ type: Type;
16
+ m: Map<Object, string>;
17
+ constructor(options: UnionOptions);
18
+ format(obj: any): string | Object;
19
+ private validField;
20
+ valid(obj: any): Promise<boolean>;
21
+ }
22
+ export declare function UnionType(options: UnionOptions): UnionField & UnionOptions;
23
+ export declare function UnionListType(options: UnionOptions): ListField;
@@ -0,0 +1,79 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.UnionListType = exports.UnionType = exports.UnionField = void 0;
4
+ const schema_1 = require("./schema");
5
+ const field_1 = require("./field");
6
+ // used to know which key in the union is valid.
7
+ // maybe there's a better way of doing this eventually
8
+ const KEY = "___valid___key___";
9
+ class UnionField extends field_1.BaseField {
10
+ constructor(options) {
11
+ super();
12
+ this.options = options;
13
+ this.type = {
14
+ dbType: schema_1.DBType.JSONB,
15
+ };
16
+ this.m = new Map();
17
+ this.type.unionFields = options.fields;
18
+ this.type.type = options.tsType;
19
+ this.type.graphQLType = options.graphQLType || options.tsType;
20
+ // TODO should throw if not nested?
21
+ if (options.jsonNotJSONB) {
22
+ this.type.dbType = schema_1.DBType.JSON;
23
+ }
24
+ }
25
+ format(obj) {
26
+ if (!(obj instanceof Object)) {
27
+ throw new Error("valid was not called");
28
+ }
29
+ const k = obj[KEY];
30
+ if (k === undefined) {
31
+ throw new Error(`need to call valid first`);
32
+ }
33
+ // now delete it since we don't need it anymore
34
+ delete obj[KEY];
35
+ const field = this.options.fields[k];
36
+ // always nested for now so pass through
37
+ return field.format(obj, true);
38
+ }
39
+ async validField(k, f, obj) {
40
+ const valid = await f.valid(obj);
41
+ return {
42
+ valid,
43
+ key: k,
44
+ };
45
+ }
46
+ async valid(obj) {
47
+ if (!(obj instanceof Object)) {
48
+ return false;
49
+ }
50
+ let promises = [];
51
+ for (const k in this.options.fields) {
52
+ const field = this.options.fields[k];
53
+ promises.push(this.validField(k, field, obj));
54
+ }
55
+ let lastKey;
56
+ let validCt = 0;
57
+ const ret = await Promise.all(promises);
58
+ for (const v of ret) {
59
+ if (v.valid) {
60
+ validCt++;
61
+ lastKey = v.key;
62
+ }
63
+ }
64
+ if (lastKey !== undefined) {
65
+ obj[KEY] = lastKey;
66
+ }
67
+ return validCt == 1;
68
+ }
69
+ }
70
+ exports.UnionField = UnionField;
71
+ function UnionType(options) {
72
+ let result = new UnionField(options);
73
+ return Object.assign(result, options);
74
+ }
75
+ exports.UnionType = UnionType;
76
+ function UnionListType(options) {
77
+ return new field_1.ListField(UnionType(options), options);
78
+ }
79
+ exports.UnionListType = UnionListType;
@@ -25,9 +25,8 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
25
25
  Object.defineProperty(exports, "__esModule", { value: true });
26
26
  const typescript_1 = __importDefault(require("typescript"));
27
27
  const path = __importStar(require("path"));
28
- const fs = __importStar(require("fs"));
29
- const json5_1 = __importDefault(require("json5"));
30
28
  const glob_1 = __importDefault(require("glob"));
29
+ const compilerOptions_1 = require("../tsc/compilerOptions");
31
30
  // TODO this should probably be its own package but for now it's here
32
31
  class Compiler {
33
32
  constructor(sourceFiles, moduleSearchLocations) {
@@ -35,7 +34,7 @@ class Compiler {
35
34
  this.moduleSearchLocations = moduleSearchLocations;
36
35
  this.regexMap = new Map();
37
36
  this.resolvers = [];
38
- this.options = this.readCompilerOptions();
37
+ this.options = (0, compilerOptions_1.readCompilerOptions)(".");
39
38
  if (this.options.paths) {
40
39
  for (let key in this.options.paths) {
41
40
  if (key === "*") {
@@ -105,22 +104,6 @@ class Compiler {
105
104
  }
106
105
  return undefined;
107
106
  }
108
- readCompilerOptions() {
109
- let json = {};
110
- try {
111
- json = json5_1.default.parse(fs.readFileSync("./tsconfig.json", {
112
- encoding: "utf8",
113
- }));
114
- }
115
- catch (e) {
116
- console.error("couldn't read tsconfig.json file");
117
- }
118
- let options = json["compilerOptions"] || {};
119
- if (options.moduleResolution === "node") {
120
- options.moduleResolution = typescript_1.default.ModuleResolutionKind.NodeJs;
121
- }
122
- return options;
123
- }
124
107
  createCompilerHost() {
125
108
  return {
126
109
  getSourceFile: this.getSourceFile,
@@ -0,0 +1 @@
1
+ export {};