getVirtual.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. 'use strict';
  2. module.exports = getVirtual;
  3. /*!
  4. * ignore
  5. */
  6. function getVirtual(schema, name) {
  7. if (schema.virtuals[name]) {
  8. return { virtual: schema.virtuals[name], path: void 0 };
  9. }
  10. const parts = name.split('.');
  11. let cur = '';
  12. let nestedSchemaPath = '';
  13. for (let i = 0; i < parts.length; ++i) {
  14. cur += (cur.length > 0 ? '.' : '') + parts[i];
  15. if (schema.virtuals[cur]) {
  16. if (i === parts.length - 1) {
  17. return { virtual: schema.virtuals[cur], path: nestedSchemaPath };
  18. }
  19. continue;
  20. }
  21. if (schema.nested[cur]) {
  22. continue;
  23. }
  24. if (schema.paths[cur] && schema.paths[cur].schema) {
  25. schema = schema.paths[cur].schema;
  26. const rest = parts.slice(i + 1).join('.');
  27. if (schema.virtuals[rest]) {
  28. if (i === parts.length - 2) {
  29. return {
  30. virtual: schema.virtuals[rest],
  31. nestedSchemaPath: [nestedSchemaPath, cur].filter(v => !!v).join('.')
  32. };
  33. }
  34. continue;
  35. }
  36. if (i + 1 < parts.length && schema.discriminators) {
  37. for (const key of Object.keys(schema.discriminators)) {
  38. const res = getVirtual(schema.discriminators[key], rest);
  39. if (res != null) {
  40. const _path = [nestedSchemaPath, cur, res.nestedSchemaPath].
  41. filter(v => !!v).join('.');
  42. return {
  43. virtual: res.virtual,
  44. nestedSchemaPath: _path
  45. };
  46. }
  47. }
  48. }
  49. nestedSchemaPath += (nestedSchemaPath.length > 0 ? '.' : '') + cur;
  50. cur = '';
  51. continue;
  52. }
  53. if (schema.discriminators) {
  54. for (const discriminatorKey of Object.keys(schema.discriminators)) {
  55. const virtualFromDiscriminator = getVirtual(schema.discriminators[discriminatorKey], name);
  56. if (virtualFromDiscriminator) return virtualFromDiscriminator;
  57. }
  58. }
  59. return null;
  60. }
  61. }