@bedrockio/model 0.20.2 → 0.21.1

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/CHANGELOG.md CHANGED
@@ -1,3 +1,11 @@
1
+ ## 0.21.1
2
+
3
+ - Fixed issues with schema loading.
4
+
5
+ ## 0.21.0
6
+
7
+ - Allow comments in schemas with .jsonc.
8
+
1
9
  ## 0.20.2
2
10
 
3
11
  - Fixed `_id: false` on validation schemas.
package/dist/cjs/index.js CHANGED
@@ -7,6 +7,7 @@ var _exportNames = {
7
7
  createSchema: true,
8
8
  loadModel: true,
9
9
  loadModelDir: true,
10
+ loadSchema: true,
10
11
  addValidators: true,
11
12
  isEqual: true
12
13
  };
@@ -40,6 +41,12 @@ Object.defineProperty(exports, "loadModelDir", {
40
41
  return _load.loadModelDir;
41
42
  }
42
43
  });
44
+ Object.defineProperty(exports, "loadSchema", {
45
+ enumerable: true,
46
+ get: function () {
47
+ return _load.loadSchema;
48
+ }
49
+ });
43
50
  var _schema = require("./schema");
44
51
  var _load = require("./load");
45
52
  var _validation = require("./validation");
package/dist/cjs/load.js CHANGED
@@ -5,8 +5,10 @@ Object.defineProperty(exports, "__esModule", {
5
5
  });
6
6
  exports.loadModel = loadModel;
7
7
  exports.loadModelDir = loadModelDir;
8
+ exports.loadSchema = loadSchema;
8
9
  var _fs = _interopRequireDefault(require("fs"));
9
10
  var _path = _interopRequireDefault(require("path"));
11
+ var _jsoncParser = require("jsonc-parser");
10
12
  var _lodash = require("lodash");
11
13
  var _mongoose = _interopRequireDefault(require("mongoose"));
12
14
  var _schema = require("./schema");
@@ -32,21 +34,77 @@ function loadModel(definition, name) {
32
34
  /**
33
35
  * Loads all model definitions in the given directory.
34
36
  * Returns the full loaded model set.
35
- * @param {string} dirPath
37
+ * @param {string} dir
36
38
  */
37
- function loadModelDir(dirPath) {
38
- const files = _fs.default.readdirSync(dirPath);
39
+ function loadModelDir(dir) {
40
+ const files = _fs.default.readdirSync(dir);
39
41
  for (const file of files) {
40
- const basename = _path.default.basename(file, '.json');
41
- if (file.match(/\.json$/)) {
42
- const filePath = _path.default.join(dirPath, file);
43
- const data = _fs.default.readFileSync(filePath, 'utf-8');
44
- const definition = JSON.parse(data);
45
- const modelName = definition.modelName || (0, _lodash.startCase)(basename).replace(/\s/g, '');
46
- if (!_mongoose.default.models[modelName]) {
47
- loadModel(definition, modelName);
48
- }
42
+ const ext = _path.default.extname(file);
43
+ if (!SCHEMA_EXTENSIONS.includes(ext)) {
44
+ continue;
45
+ }
46
+ const {
47
+ name: basename
48
+ } = _path.default.parse(file);
49
+ const definition = loadDefinition(basename, dir);
50
+ const modelName = getModelName(definition, basename);
51
+ if (!_mongoose.default.models[modelName]) {
52
+ loadModel(definition, modelName);
49
53
  }
50
54
  }
51
55
  return _mongoose.default.models;
56
+ }
57
+
58
+ /**
59
+ * Loads the schema from a .json or .jsonc file.
60
+ * @param {string} name - The model or schema name.
61
+ * @param {string} [dir] - The schema directory (defaults to `src/models/definitions`)
62
+ */
63
+ function loadSchema(name, dir) {
64
+ const definition = loadDefinition(name, dir);
65
+ return (0, _schema.createSchema)(definition);
66
+ }
67
+ const DEFINITION_DIR = 'src/models/definitions';
68
+ const SCHEMA_EXTENSIONS = ['.json', '.jsonc'];
69
+ function loadDefinition(name, dir) {
70
+ const {
71
+ filepath,
72
+ ext
73
+ } = resolvePath(name, dir);
74
+ const content = _fs.default.readFileSync(filepath, 'utf-8');
75
+ return ext === '.jsonc' ? (0, _jsoncParser.parse)(content) : JSON.parse(content);
76
+ }
77
+ function resolvePath(name, dir = DEFINITION_DIR) {
78
+ if (name.includes('.')) {
79
+ throw new Error('Name should not include extension');
80
+ }
81
+ let filename = (0, _lodash.kebabCase)(name);
82
+ let ext = _path.default.extname(name);
83
+ if (!ext) {
84
+ ext = resolveExtension(filename, dir);
85
+ if (ext) {
86
+ filename += ext;
87
+ } else {
88
+ throw new Error(`No .json or .jsonc file found for: ${name}`);
89
+ }
90
+ }
91
+ if (!SCHEMA_EXTENSIONS.includes(ext)) {
92
+ throw new Error(`Schema files must be .json or .jsonc`);
93
+ }
94
+ const filepath = _path.default.resolve(dir, filename);
95
+ return {
96
+ ext,
97
+ filepath
98
+ };
99
+ }
100
+ function resolveExtension(filename, dir) {
101
+ for (const ext of SCHEMA_EXTENSIONS) {
102
+ const filepath = _path.default.resolve(dir, filename + ext);
103
+ if (_fs.default.existsSync(filepath)) {
104
+ return ext;
105
+ }
106
+ }
107
+ }
108
+ function getModelName(definition, basename) {
109
+ return definition.modelName || (0, _lodash.startCase)(basename).replace(/\s/g, '');
52
110
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bedrockio/model",
3
- "version": "0.20.2",
3
+ "version": "0.21.1",
4
4
  "description": "Bedrock utilities for model creation.",
5
5
  "type": "module",
6
6
  "scripts": {
@@ -27,6 +27,7 @@
27
27
  },
28
28
  "dependencies": {
29
29
  "@bedrockio/logger": "^1.1.1",
30
+ "jsonc-parser": "^3.3.1",
30
31
  "lodash": "^4.17.21"
31
32
  },
32
33
  "peerDependencies": {
package/src/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  export { createSchema } from './schema';
2
- export { loadModel, loadModelDir } from './load';
2
+ export { loadModel, loadModelDir, loadSchema } from './load';
3
3
  export { addValidators } from './validation';
4
4
  export { isEqual } from './utils';
5
5
  export * from './testing';
package/src/load.js CHANGED
@@ -1,6 +1,8 @@
1
1
  import fs from 'fs';
2
2
  import path from 'path';
3
3
 
4
+ import { parse as parseWithComments } from 'jsonc-parser';
5
+ import { kebabCase } from 'lodash';
4
6
  import { startCase } from 'lodash';
5
7
  import mongoose from 'mongoose';
6
8
 
@@ -27,22 +29,86 @@ export function loadModel(definition, name) {
27
29
  /**
28
30
  * Loads all model definitions in the given directory.
29
31
  * Returns the full loaded model set.
30
- * @param {string} dirPath
32
+ * @param {string} dir
31
33
  */
32
- export function loadModelDir(dirPath) {
33
- const files = fs.readdirSync(dirPath);
34
+ export function loadModelDir(dir) {
35
+ const files = fs.readdirSync(dir);
34
36
  for (const file of files) {
35
- const basename = path.basename(file, '.json');
36
- if (file.match(/\.json$/)) {
37
- const filePath = path.join(dirPath, file);
38
- const data = fs.readFileSync(filePath, 'utf-8');
39
- const definition = JSON.parse(data);
40
- const modelName =
41
- definition.modelName || startCase(basename).replace(/\s/g, '');
42
- if (!mongoose.models[modelName]) {
43
- loadModel(definition, modelName);
44
- }
37
+ const ext = path.extname(file);
38
+
39
+ if (!SCHEMA_EXTENSIONS.includes(ext)) {
40
+ continue;
41
+ }
42
+
43
+ const { name: basename } = path.parse(file);
44
+ const definition = loadDefinition(basename, dir);
45
+ const modelName = getModelName(definition, basename);
46
+
47
+ if (!mongoose.models[modelName]) {
48
+ loadModel(definition, modelName);
45
49
  }
46
50
  }
47
51
  return mongoose.models;
48
52
  }
53
+
54
+ /**
55
+ * Loads the schema from a .json or .jsonc file.
56
+ * @param {string} name - The model or schema name.
57
+ * @param {string} [dir] - The schema directory (defaults to `src/models/definitions`)
58
+ */
59
+ export function loadSchema(name, dir) {
60
+ const definition = loadDefinition(name, dir);
61
+ return createSchema(definition);
62
+ }
63
+
64
+ const DEFINITION_DIR = 'src/models/definitions';
65
+ const SCHEMA_EXTENSIONS = ['.json', '.jsonc'];
66
+
67
+ function loadDefinition(name, dir) {
68
+ const { filepath, ext } = resolvePath(name, dir);
69
+ const content = fs.readFileSync(filepath, 'utf-8');
70
+ return ext === '.jsonc' ? parseWithComments(content) : JSON.parse(content);
71
+ }
72
+
73
+ function resolvePath(name, dir = DEFINITION_DIR) {
74
+ if (name.includes('.')) {
75
+ throw new Error('Name should not include extension');
76
+ }
77
+
78
+ let filename = kebabCase(name);
79
+ let ext = path.extname(name);
80
+
81
+ if (!ext) {
82
+ ext = resolveExtension(filename, dir);
83
+
84
+ if (ext) {
85
+ filename += ext;
86
+ } else {
87
+ throw new Error(`No .json or .jsonc file found for: ${name}`);
88
+ }
89
+ }
90
+
91
+ if (!SCHEMA_EXTENSIONS.includes(ext)) {
92
+ throw new Error(`Schema files must be .json or .jsonc`);
93
+ }
94
+
95
+ const filepath = path.resolve(dir, filename);
96
+
97
+ return {
98
+ ext,
99
+ filepath,
100
+ };
101
+ }
102
+
103
+ function resolveExtension(filename, dir) {
104
+ for (const ext of SCHEMA_EXTENSIONS) {
105
+ const filepath = path.resolve(dir, filename + ext);
106
+ if (fs.existsSync(filepath)) {
107
+ return ext;
108
+ }
109
+ }
110
+ }
111
+
112
+ function getModelName(definition, basename) {
113
+ return definition.modelName || startCase(basename).replace(/\s/g, '');
114
+ }
@@ -3,5 +3,5 @@ export { addValidators } from "./validation";
3
3
  export { isEqual } from "./utils";
4
4
  export * from "./testing";
5
5
  export * from "./errors";
6
- export { loadModel, loadModelDir } from "./load";
6
+ export { loadModel, loadModelDir, loadSchema } from "./load";
7
7
  //# sourceMappingURL=index.d.ts.map
@@ -8,8 +8,30 @@ export function loadModel(definition: object, name: string): any;
8
8
  /**
9
9
  * Loads all model definitions in the given directory.
10
10
  * Returns the full loaded model set.
11
- * @param {string} dirPath
11
+ * @param {string} dir
12
12
  */
13
- export function loadModelDir(dirPath: string): mongoose.Models;
13
+ export function loadModelDir(dir: string): mongoose.Models;
14
+ /**
15
+ * Loads the schema from a .json or .jsonc file.
16
+ * @param {string} name - The model or schema name.
17
+ * @param {string} [dir] - The schema directory (defaults to `src/models/definitions`)
18
+ */
19
+ export function loadSchema(name: string, dir?: string): mongoose.Schema<any, mongoose.Model<any, any, any, any, any, any>, any, any, any, any, mongoose.DefaultSchemaOptions, {
20
+ [x: number]: unknown;
21
+ [x: symbol]: unknown;
22
+ [x: string]: unknown;
23
+ }, mongoose.Document<unknown, {}, mongoose.FlatRecord<{
24
+ [x: number]: unknown;
25
+ [x: symbol]: unknown;
26
+ [x: string]: unknown;
27
+ }>, any, mongoose.ResolveSchemaOptions<mongoose.DefaultSchemaOptions>> & mongoose.FlatRecord<{
28
+ [x: number]: unknown;
29
+ [x: symbol]: unknown;
30
+ [x: string]: unknown;
31
+ }> & Required<{
32
+ _id: unknown;
33
+ }> & {
34
+ __v: number;
35
+ }>;
14
36
  import mongoose from 'mongoose';
15
37
  //# sourceMappingURL=load.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"load.d.ts","sourceRoot":"","sources":["../../src/load.js"],"names":[],"mappings":"AAQA;;;;;GAKG;AACH,sCAJW,MAAM,QACN,MAAM,OAahB;AAED;;;;GAIG;AACH,sCAFW,MAAM,mBAkBhB;qBA3CoB,UAAU"}
1
+ {"version":3,"file":"load.d.ts","sourceRoot":"","sources":["../../src/load.js"],"names":[],"mappings":"AAUA;;;;;GAKG;AACH,sCAJW,MAAM,QACN,MAAM,OAahB;AAED;;;;GAIG;AACH,kCAFW,MAAM,mBAoBhB;AAED;;;;GAIG;AACH,iCAHW,MAAM,QACN,MAAM;;;;;;;;;;;;;;;;GAKhB;qBAvDoB,UAAU"}