* Applies schema type transforms to `json`. * * @param {Document} self * @param {object} json * @return {object} `json` * @api private
(self, json)
| 4584 | */ |
| 4585 | |
| 4586 | function applySchemaTypeTransforms(self, json) { |
| 4587 | const schema = self.$__schema; |
| 4588 | const paths = schema.pathsWithTransforms(); |
| 4589 | const cur = self._doc; |
| 4590 | |
| 4591 | if (!cur || !paths) { |
| 4592 | return json; |
| 4593 | } |
| 4594 | |
| 4595 | for (const path of paths) { |
| 4596 | const schematype = schema.paths[path]; |
| 4597 | const topLevelTransformFunction = schematype.options.transform ?? schematype.constructor?.defaultOptions?.transform; |
| 4598 | const embeddedSchemaTypeTransformFunction = schematype.embeddedSchemaType?.options?.transform |
| 4599 | ?? schematype.embeddedSchemaType?.constructor?.defaultOptions?.transform; |
| 4600 | if (typeof topLevelTransformFunction === 'function') { |
| 4601 | const val = self.$get(path); |
| 4602 | if (val === undefined) { |
| 4603 | continue; |
| 4604 | } |
| 4605 | const transformedValue = topLevelTransformFunction.call(self, val); |
| 4606 | throwErrorIfPromise(path, transformedValue); |
| 4607 | utils.setValue(path, transformedValue, json); |
| 4608 | } else if (typeof embeddedSchemaTypeTransformFunction === 'function') { |
| 4609 | const val = self.$get(path); |
| 4610 | if (val === undefined) { |
| 4611 | continue; |
| 4612 | } |
| 4613 | const vals = [].concat(val); |
| 4614 | for (let i = 0; i < vals.length; ++i) { |
| 4615 | const transformedValue = embeddedSchemaTypeTransformFunction.call(self, vals[i]); |
| 4616 | vals[i] = transformedValue; |
| 4617 | throwErrorIfPromise(path, transformedValue); |
| 4618 | } |
| 4619 | |
| 4620 | json[path] = vals; |
| 4621 | } |
| 4622 | } |
| 4623 | |
| 4624 | return json; |
| 4625 | } |
| 4626 | |
| 4627 | function throwErrorIfPromise(path, transformedValue) { |
| 4628 | if (isPromise(transformedValue)) { |
no test coverage detected