e22m4u 1 день назад
Родитель
Сommit
47e5229efa

+ 4 - 4
README.md

@@ -45,12 +45,12 @@ projectData(schemaOrFactory, data, [options])
 
 
 **`schemaOrFactory`**  
 **`schemaOrFactory`**  
 
 
-*Тип: `object` | `Function` | `string` | `symbol`*
+*Тип: `object` | `Function` | `string`*
 
 
 Определяет правила проекции. Принимает:
 Определяет правила проекции. Принимает:
 - `object`: объект схемы проекции;
 - `object`: объект схемы проекции;
-- `Function`: фабрика, возвращающая схему (или ключ схемы);
-- `string | symbol`: ключ для поиска схемы через функцию `resolver`;
+- `Function`: фабрика, возвращающая схему (или имя схемы);
+- `string`: имя для поиска схемы через функцию `resolver`;
 
 
 **`data`**  
 **`data`**  
 
 
@@ -67,7 +67,7 @@ projectData(schemaOrFactory, data, [options])
 
 
 - `strict?: boolean`: включает строгий режим;
 - `strict?: boolean`: включает строгий режим;
 - `scope?: string`: имя активной области проекции;
 - `scope?: string`: имя активной области проекции;
-- `resolver?: Function`: функция для получения схемы по ключу;
+- `resolver?: Function`: функция для получения схемы по имени;
 
 
 **Возвращаемое значение:**
 **Возвращаемое значение:**
 
 

+ 13 - 13
dist/cjs/index.cjs

@@ -66,9 +66,9 @@ function validateProjectionSchema(schema, shallowMode = false) {
       );
       );
     }
     }
     if (options.schema !== void 0) {
     if (options.schema !== void 0) {
-      if (!options.schema || typeof options.schema !== "object" && typeof options.schema !== "function" && typeof options.schema !== "string" && typeof options.schema !== "symbol" || Array.isArray(options.schema)) {
+      if (!options.schema || typeof options.schema !== "object" && typeof options.schema !== "function" && typeof options.schema !== "string" || Array.isArray(options.schema)) {
         throw new import_js_format.InvalidArgumentError(
         throw new import_js_format.InvalidArgumentError(
-          "Embedded schema must be an Object, a Function, a non-empty String or a Symbol, but %v was given.",
+          "Embedded schema must be an Object, a Function or a non-empty String, but %v was given.",
           options.schema
           options.schema
         );
         );
       }
       }
@@ -113,9 +113,9 @@ __name(validateProjectionSchema, "validateProjectionSchema");
 
 
 // src/project-data.js
 // src/project-data.js
 function projectData(schemaOrFactory, data, options) {
 function projectData(schemaOrFactory, data, options) {
-  if (!schemaOrFactory || typeof schemaOrFactory !== "object" && typeof schemaOrFactory !== "function" && typeof schemaOrFactory !== "string" && typeof schemaOrFactory !== "symbol" || Array.isArray(schemaOrFactory)) {
+  if (!schemaOrFactory || typeof schemaOrFactory !== "object" && typeof schemaOrFactory !== "function" && typeof schemaOrFactory !== "string" || Array.isArray(schemaOrFactory)) {
     throw new import_js_format2.InvalidArgumentError(
     throw new import_js_format2.InvalidArgumentError(
-      "Projection schema must be an Object, a Function, a non-empty String or a Symbol, but %v was given.",
+      "Projection schema must be an Object, a Function or a non-empty String, but %v was given.",
       schemaOrFactory
       schemaOrFactory
     );
     );
   }
   }
@@ -147,25 +147,25 @@ function projectData(schemaOrFactory, data, options) {
   }
   }
   const strict = Boolean(options && options.strict);
   const strict = Boolean(options && options.strict);
   const scope = options && options.scope || void 0;
   const scope = options && options.scope || void 0;
-  let schemaOrKey = schemaOrFactory;
+  let schemaOrName = schemaOrFactory;
   if (typeof schemaOrFactory === "function") {
   if (typeof schemaOrFactory === "function") {
-    schemaOrKey = schemaOrFactory();
-    if (!schemaOrKey || typeof schemaOrKey !== "object" && typeof schemaOrKey !== "string" && typeof schemaOrKey !== "symbol" || Array.isArray(schemaOrKey)) {
+    schemaOrName = schemaOrFactory();
+    if (!schemaOrName || typeof schemaOrName !== "object" && typeof schemaOrName !== "string" || Array.isArray(schemaOrName)) {
       throw new import_js_format2.InvalidArgumentError(
       throw new import_js_format2.InvalidArgumentError(
-        "Projection schema factory must return an Object, a non-empty String or a Symbol, but %v was given.",
-        schemaOrKey
+        "Projection schema factory must return an Object or a non-empty String, but %v was given.",
+        schemaOrName
       );
       );
     }
     }
   }
   }
-  let schema = schemaOrKey;
-  if (schemaOrKey && (typeof schemaOrKey === "string" || typeof schemaOrKey === "symbol")) {
+  let schema = schemaOrName;
+  if (schemaOrName && typeof schemaOrName === "string") {
     if (!options || !options.resolver) {
     if (!options || !options.resolver) {
       throw new import_js_format2.InvalidArgumentError(
       throw new import_js_format2.InvalidArgumentError(
         "Unable to resolve the projection schema %v without a provided resolver.",
         "Unable to resolve the projection schema %v without a provided resolver.",
-        schemaOrKey
+        schemaOrName
       );
       );
     }
     }
-    schema = options.resolver(schemaOrKey);
+    schema = options.resolver(schemaOrName);
     if (!schema || typeof schema !== "object" || Array.isArray(schema)) {
     if (!schema || typeof schema !== "object" || Array.isArray(schema)) {
       throw new import_js_format2.InvalidArgumentError(
       throw new import_js_format2.InvalidArgumentError(
         "Projection schema resolver must return an Object, but %v was given.",
         "Projection schema resolver must return an Object, but %v was given.",

+ 2 - 1
package.json

@@ -38,7 +38,8 @@
     "prepare": "husky"
     "prepare": "husky"
   },
   },
   "dependencies": {
   "dependencies": {
-    "@e22m4u/js-format": "~0.3.2"
+    "@e22m4u/js-format": "~0.3.2",
+    "@e22m4u/js-service": "^0.5.1"
   },
   },
   "devDependencies": {
   "devDependencies": {
     "@commitlint/cli": "~20.2.0",
     "@commitlint/cli": "~20.2.0",

+ 3 - 3
src/project-data.d.ts

@@ -1,6 +1,6 @@
 import {
 import {
   ProjectionSchema,
   ProjectionSchema,
-  ProjectionSchemaKey,
+  ProjectionSchemaName,
   ProjectionSchemaFactory,
   ProjectionSchemaFactory,
 } from './projection-schema.js';
 } from './projection-schema.js';
 
 
@@ -8,7 +8,7 @@ import {
  * Projection schema resolver.
  * Projection schema resolver.
  */
  */
 export type ProjectionSchemaResolver = (
 export type ProjectionSchemaResolver = (
-  schemaKey: ProjectionSchemaKey,
+  schemaName: ProjectionSchemaName,
 ) => ProjectionSchema;
 ) => ProjectionSchema;
 
 
 /**
 /**
@@ -31,7 +31,7 @@ export declare function projectData<T>(
   schemaOrFactory:
   schemaOrFactory:
     | ProjectionSchema
     | ProjectionSchema
     | ProjectionSchemaFactory
     | ProjectionSchemaFactory
-    | ProjectionSchemaKey,
+    | ProjectionSchemaName,
   data: T,
   data: T,
   options?: ProjectDataOptions,
   options?: ProjectDataOptions,
 ): T;
 ): T;

+ 19 - 25
src/project-data.js

@@ -15,13 +15,12 @@ export function projectData(schemaOrFactory, data, options) {
     !schemaOrFactory ||
     !schemaOrFactory ||
     (typeof schemaOrFactory !== 'object' &&
     (typeof schemaOrFactory !== 'object' &&
       typeof schemaOrFactory !== 'function' &&
       typeof schemaOrFactory !== 'function' &&
-      typeof schemaOrFactory !== 'string' &&
-      typeof schemaOrFactory !== 'symbol') ||
+      typeof schemaOrFactory !== 'string') ||
     Array.isArray(schemaOrFactory)
     Array.isArray(schemaOrFactory)
   ) {
   ) {
     throw new InvalidArgumentError(
     throw new InvalidArgumentError(
-      'Projection schema must be an Object, a Function, ' +
-        'a non-empty String or a Symbol, but %v was given.',
+      'Projection schema must be an Object, a Function ' +
+        'or a non-empty String, but %v was given.',
       schemaOrFactory,
       schemaOrFactory,
     );
     );
   }
   }
@@ -65,42 +64,37 @@ export function projectData(schemaOrFactory, data, options) {
   const scope = (options && options.scope) || undefined;
   const scope = (options && options.scope) || undefined;
   // если вместо схемы передана фабрика,
   // если вместо схемы передана фабрика,
   // то извлекается фабричное значение
   // то извлекается фабричное значение
-  let schemaOrKey = schemaOrFactory;
+  let schemaOrName = schemaOrFactory;
   if (typeof schemaOrFactory === 'function') {
   if (typeof schemaOrFactory === 'function') {
-    schemaOrKey = schemaOrFactory();
-    // если фабричное значение не является объектом,
-    // строкой или символом, то выбрасывается ошибка
+    schemaOrName = schemaOrFactory();
+    // если фабричное значение не является объектом
+    // или строкой, то выбрасывается ошибка
     if (
     if (
-      !schemaOrKey ||
-      (typeof schemaOrKey !== 'object' &&
-        typeof schemaOrKey !== 'string' &&
-        typeof schemaOrKey !== 'symbol') ||
-      Array.isArray(schemaOrKey)
+      !schemaOrName ||
+      (typeof schemaOrName !== 'object' && typeof schemaOrName !== 'string') ||
+      Array.isArray(schemaOrName)
     ) {
     ) {
       throw new InvalidArgumentError(
       throw new InvalidArgumentError(
-        'Projection schema factory must return an Object, ' +
-          'a non-empty String or a Symbol, but %v was given.',
-        schemaOrKey,
+        'Projection schema factory must return an Object ' +
+          'or a non-empty String, but %v was given.',
+        schemaOrName,
       );
       );
     }
     }
   }
   }
-  // если вместо схемы передана строка или символ,
-  // то значение передается в разрешающую функцию
-  let schema = schemaOrKey;
-  if (
-    schemaOrKey &&
-    (typeof schemaOrKey === 'string' || typeof schemaOrKey === 'symbol')
-  ) {
+  // если вместо схемы передана строка,
+  // то строка передается в разрешающую функцию
+  let schema = schemaOrName;
+  if (schemaOrName && typeof schemaOrName === 'string') {
     // если разрешающая функция не определена,
     // если разрешающая функция не определена,
     // то выбрасывается ошибка
     // то выбрасывается ошибка
     if (!options || !options.resolver) {
     if (!options || !options.resolver) {
       throw new InvalidArgumentError(
       throw new InvalidArgumentError(
         'Unable to resolve the projection schema %v ' +
         'Unable to resolve the projection schema %v ' +
           'without a provided resolver.',
           'without a provided resolver.',
-        schemaOrKey,
+        schemaOrName,
       );
       );
     }
     }
-    schema = options.resolver(schemaOrKey);
+    schema = options.resolver(schemaOrName);
     // если не удалось извлечь схему проекции,
     // если не удалось извлечь схему проекции,
     // то выбрасывается ошибка
     // то выбрасывается ошибка
     if (!schema || typeof schema !== 'object' || Array.isArray(schema)) {
     if (!schema || typeof schema !== 'object' || Array.isArray(schema)) {

+ 8 - 82
src/project-data.spec.js

@@ -7,8 +7,8 @@ describe('projectData', function () {
     const throwable = v => () => projectData(v, {});
     const throwable = v => () => projectData(v, {});
     const error = s =>
     const error = s =>
       format(
       format(
-        'Projection schema must be an Object, a Function, ' +
-          'a non-empty String or a Symbol, but %s was given.',
+        'Projection schema must be an Object, a Function ' +
+          'or a non-empty String, but %s was given.',
         s,
         s,
       );
       );
     expect(throwable('')).to.throw(error('""'));
     expect(throwable('')).to.throw(error('""'));
@@ -152,8 +152,8 @@ describe('projectData', function () {
       const throwable = v => () => projectData(() => v, {});
       const throwable = v => () => projectData(() => v, {});
       const error = s =>
       const error = s =>
         format(
         format(
-          'Projection schema factory must return an Object, ' +
-            'a non-empty String or a Symbol, but %s was given.',
+          'Projection schema factory must return an Object ' +
+            'or a non-empty String, but %s was given.',
           s,
           s,
         );
         );
       expect(throwable('')).to.throw(error('""'));
       expect(throwable('')).to.throw(error('""'));
@@ -166,7 +166,6 @@ describe('projectData', function () {
       expect(throwable(undefined)).to.throw(error('undefined'));
       expect(throwable(undefined)).to.throw(error('undefined'));
       projectData(() => ({}), {});
       projectData(() => ({}), {});
       projectData(() => 'mySchema', {}, {resolver: () => ({})});
       projectData(() => 'mySchema', {}, {resolver: () => ({})});
-      projectData(() => Symbol('mySchema'), {}, {resolver: () => ({})});
     });
     });
 
 
     it('should resolve a schema object from the given factory', function () {
     it('should resolve a schema object from the given factory', function () {
@@ -195,7 +194,7 @@ describe('projectData', function () {
     });
     });
   });
   });
 
 
-  describe('string key', function () {
+  describe('named schema', function () {
     it('should throw an error if the schema resolver returns an invalid value', function () {
     it('should throw an error if the schema resolver returns an invalid value', function () {
       const throwable = v => () =>
       const throwable = v => () =>
         projectData('mySchema', {}, {resolver: () => v});
         projectData('mySchema', {}, {resolver: () => v});
@@ -216,7 +215,7 @@ describe('projectData', function () {
       throwable({})();
       throwable({})();
     });
     });
 
 
-    it('should throw an error if no schema resolver is provided when a string key is given', function () {
+    it('should throw an error if no schema resolver is provided when a schema name is given', function () {
       const throwable = () => projectData('mySchema', {});
       const throwable = () => projectData('mySchema', {});
       expect(throwable).to.throw(
       expect(throwable).to.throw(
         'Unable to resolve the projection schema "mySchema" ' +
         'Unable to resolve the projection schema "mySchema" ' +
@@ -224,7 +223,7 @@ describe('projectData', function () {
       );
       );
     });
     });
 
 
-    it('should pass the string key to the schema resolver and project the given data', function () {
+    it('should pass the schema name to the schema resolver and project the given data', function () {
       let invoked = 0;
       let invoked = 0;
       const resolver = key => {
       const resolver = key => {
         expect(key).to.be.eq('mySchema');
         expect(key).to.be.eq('mySchema');
@@ -252,7 +251,7 @@ describe('projectData', function () {
       expect(invoked).to.be.eq(1);
       expect(invoked).to.be.eq(1);
     });
     });
 
 
-    it('should resolve the string key from the schema factory', function () {
+    it('should use the schema name from the schema factory', function () {
       let invoked = 0;
       let invoked = 0;
       const resolver = key => {
       const resolver = key => {
         expect(key).to.be.eq('mySchema');
         expect(key).to.be.eq('mySchema');
@@ -265,79 +264,6 @@ describe('projectData', function () {
     });
     });
   });
   });
 
 
-  describe('symbol key', function () {
-    it('should throw an error if the schema resolver returns an invalid value', function () {
-      const throwable = v => () =>
-        projectData(Symbol('mySchema'), {}, {resolver: () => v});
-      const error = s =>
-        format(
-          'Projection schema resolver must return an Object, but %s was given.',
-          s,
-        );
-      expect(throwable('str')).to.throw(error('"str"'));
-      expect(throwable('')).to.throw(error('""'));
-      expect(throwable(10)).to.throw(error('10'));
-      expect(throwable(0)).to.throw(error('0'));
-      expect(throwable(true)).to.throw(error('true'));
-      expect(throwable(false)).to.throw(error('false'));
-      expect(throwable([])).to.throw(error('Array'));
-      expect(throwable(null)).to.throw(error('null'));
-      expect(throwable(undefined)).to.throw(error('undefined'));
-      throwable({})();
-    });
-
-    it('should throw an error if no schema resolver is provided when a symbol key is given', function () {
-      const throwable = () => projectData(Symbol('mySchema'), {});
-      expect(throwable).to.throw(
-        'Unable to resolve the projection schema Symbol("mySchema") ' +
-          'without a provided resolver.',
-      );
-    });
-
-    it('should pass the symbol key to the schema resolver and project the given data', function () {
-      let invoked = 0;
-      const symbolKey = Symbol('mySchema');
-      const resolver = key => {
-        expect(key).to.be.eq(symbolKey);
-        invoked++;
-        return {foo: true, bar: false};
-      };
-      const res = projectData(symbolKey, {foo: 10, bar: 20}, {resolver});
-      expect(res).to.be.eql({foo: 10});
-      expect(invoked).to.be.eq(1);
-    });
-
-    it('should use the schema resolver in the nested schema', function () {
-      let invoked = 0;
-      const symbolKey = Symbol('mySchema');
-      const resolver = key => {
-        expect(key).to.be.eq(symbolKey);
-        invoked++;
-        return {baz: true, qux: false};
-      };
-      const res = projectData(
-        {foo: true, bar: {schema: symbolKey}},
-        {foo: 10, bar: {baz: 20, qux: 30}},
-        {resolver},
-      );
-      expect(res).to.be.eql({foo: 10, bar: {baz: 20}});
-      expect(invoked).to.be.eq(1);
-    });
-
-    it('should resolve the symbol key from the schema factory', function () {
-      let invoked = 0;
-      const symbolKey = Symbol('mySchema');
-      const resolver = key => {
-        expect(key).to.be.eq(symbolKey);
-        invoked++;
-        return {foo: true, bar: false};
-      };
-      const res = projectData(() => symbolKey, {foo: 10, bar: 20}, {resolver});
-      expect(res).to.be.eql({foo: 10});
-      expect(invoked).to.be.eq(1);
-    });
-  });
-
   describe('strict mode', function () {
   describe('strict mode', function () {
     it('should preserve fields not defined in the schema when the strict option is false', function () {
     it('should preserve fields not defined in the schema when the strict option is false', function () {
       const res = projectData({}, {foo: 10});
       const res = projectData({}, {foo: 10});

+ 4 - 4
src/projection-schema.d.ts

@@ -7,16 +7,16 @@ export type ProjectionSchema = {
 };
 };
 
 
 /**
 /**
- * Projection schema key.
+ * Projection schema name.
  */
  */
-export type ProjectionSchemaKey = string | symbol;
+export type ProjectionSchemaName = string;
 
 
 /**
 /**
  * Projection schema factory.
  * Projection schema factory.
  */
  */
 export type ProjectionSchemaFactory = () =>
 export type ProjectionSchemaFactory = () =>
   | ProjectionSchema
   | ProjectionSchema
-  | ProjectionSchemaKey;
+  | ProjectionSchemaName;
 
 
 /**
 /**
  * Projection schema property options.
  * Projection schema property options.
@@ -24,7 +24,7 @@ export type ProjectionSchemaFactory = () =>
 export type ProjectionSchemaPropertyOptions = {
 export type ProjectionSchemaPropertyOptions = {
   select?: boolean;
   select?: boolean;
   scopes?: ProjectionSchemaScopes;
   scopes?: ProjectionSchemaScopes;
-  schema?: ProjectionSchema | ProjectionSchemaFactory | ProjectionSchemaKey;
+  schema?: ProjectionSchema | ProjectionSchemaFactory | ProjectionSchemaName;
 };
 };
 
 
 /**
 /**

+ 3 - 4
src/validate-projection-schema.js

@@ -54,13 +54,12 @@ export function validateProjectionSchema(schema, shallowMode = false) {
         !options.schema ||
         !options.schema ||
         (typeof options.schema !== 'object' &&
         (typeof options.schema !== 'object' &&
           typeof options.schema !== 'function' &&
           typeof options.schema !== 'function' &&
-          typeof options.schema !== 'string' &&
-          typeof options.schema !== 'symbol') ||
+          typeof options.schema !== 'string') ||
         Array.isArray(options.schema)
         Array.isArray(options.schema)
       ) {
       ) {
         throw new InvalidArgumentError(
         throw new InvalidArgumentError(
-          'Embedded schema must be an Object, a Function, ' +
-            'a non-empty String or a Symbol, but %v was given.',
+          'Embedded schema must be an Object, a Function ' +
+            'or a non-empty String, but %v was given.',
           options.schema,
           options.schema,
         );
         );
       }
       }

+ 2 - 3
src/validate-projection-schema.spec.js

@@ -77,8 +77,8 @@ describe('validateProjectionSchema', function () {
     const throwable = v => () => validateProjectionSchema({foo: {schema: v}});
     const throwable = v => () => validateProjectionSchema({foo: {schema: v}});
     const error = s =>
     const error = s =>
       format(
       format(
-        'Embedded schema must be an Object, a Function, ' +
-          'a non-empty String or a Symbol, but %s was given.',
+        'Embedded schema must be an Object, a Function ' +
+          'or a non-empty String, but %s was given.',
         s,
         s,
       );
       );
     expect(throwable('')).to.throw(error('""'));
     expect(throwable('')).to.throw(error('""'));
@@ -91,7 +91,6 @@ describe('validateProjectionSchema', function () {
     throwable('mySchema')();
     throwable('mySchema')();
     throwable({})();
     throwable({})();
     throwable(() => ({}))();
     throwable(() => ({}))();
-    throwable(Symbol('mySchema'))();
     throwable(undefined)();
     throwable(undefined)();
   });
   });