modelJsonAttributes.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. const { asArray, isObject, flatten } = require('../utils/objectUtils');
  2. function parseJsonAttributes(json, ModelClass) {
  3. const jsonAttr = ModelClass.getJsonAttributes();
  4. if (jsonAttr.length) {
  5. // JSON attributes may be returned as strings depending on the database and
  6. // the database client. Convert them to objects here.
  7. for (let i = 0, l = jsonAttr.length; i < l; ++i) {
  8. const attr = jsonAttr[i];
  9. const value = json[attr];
  10. if (typeof value === 'string') {
  11. const parsed = tryParseJson(value);
  12. // tryParseJson returns undefined if parsing failed.
  13. if (parsed !== undefined) {
  14. json[attr] = parsed;
  15. }
  16. }
  17. }
  18. }
  19. return json;
  20. }
  21. function formatJsonAttributes(json, ModelClass) {
  22. const jsonAttr = ModelClass.getJsonAttributes();
  23. if (jsonAttr.length) {
  24. // All database clients want JSON columns as strings. Do the conversion here.
  25. for (let i = 0, l = jsonAttr.length; i < l; ++i) {
  26. const attr = jsonAttr[i];
  27. const value = json[attr];
  28. if (isObject(value)) {
  29. json[attr] = JSON.stringify(value);
  30. }
  31. }
  32. }
  33. return json;
  34. }
  35. function getJsonAttributes(ModelClass) {
  36. let jsonAttributes = ModelClass.jsonAttributes;
  37. if (Array.isArray(jsonAttributes)) {
  38. return jsonAttributes;
  39. }
  40. jsonAttributes = [];
  41. if (ModelClass.getJsonSchema()) {
  42. const props = ModelClass.getJsonSchema().properties || {};
  43. const propNames = Object.keys(props);
  44. for (let i = 0, l = propNames.length; i < l; ++i) {
  45. const propName = propNames[i];
  46. const prop = props[propName];
  47. let types = asArray(prop.type).filter(it => !!it);
  48. if (types.length === 0 && Array.isArray(prop.anyOf)) {
  49. types = flatten(prop.anyOf.map(it => it.type));
  50. }
  51. if (types.length === 0 && Array.isArray(prop.oneOf)) {
  52. types = flatten(prop.oneOf.map(it => it.type));
  53. }
  54. if (types.indexOf('object') !== -1 || types.indexOf('array') !== -1) {
  55. jsonAttributes.push(propName);
  56. }
  57. }
  58. }
  59. return jsonAttributes;
  60. }
  61. function tryParseJson(maybeJsonStr) {
  62. try {
  63. return JSON.parse(maybeJsonStr);
  64. } catch (err) {
  65. return undefined;
  66. }
  67. }
  68. module.exports = {
  69. parseJsonAttributes,
  70. formatJsonAttributes,
  71. getJsonAttributes
  72. };