ce5de926d46c92d3f98559b6cfd1d3c79d9255c344fda6e6b028c609db0134fe80b224393710c413d6223307dc43272b41b0a68a643cee7689883d8b995aa7 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. /*
  2. ## toJSONSchema
  3. 把 Mock.js 风格的数据模板转换成 JSON Schema。
  4. > [JSON Schema](http://json-schema.org/)
  5. */
  6. var Constant = require('../constant')
  7. var Util = require('../util')
  8. var Parser = require('../parser')
  9. function toJSONSchema(template, name, path /* Internal Use Only */ ) {
  10. // type rule properties items
  11. path = path || []
  12. var result = {
  13. name: typeof name === 'string' ? name.replace(Constant.RE_KEY, '$1') : name,
  14. template: template,
  15. type: Util.type(template), // 可能不准确,例如 { 'name|1': [{}, {} ...] }
  16. rule: Parser.parse(name)
  17. }
  18. result.path = path.slice(0)
  19. result.path.push(name === undefined ? 'ROOT' : result.name)
  20. switch (result.type) {
  21. case 'array':
  22. result.items = []
  23. Util.each(template, function(value, index) {
  24. result.items.push(
  25. toJSONSchema(value, index, result.path)
  26. )
  27. })
  28. break
  29. case 'object':
  30. result.properties = []
  31. Util.each(template, function(value, name) {
  32. result.properties.push(
  33. toJSONSchema(value, name, result.path)
  34. )
  35. })
  36. break
  37. }
  38. return result
  39. }
  40. module.exports = toJSONSchema