根據 json-schema 規範封裝一個 data-schema-tool

這是我本身寫的一個根據模型構建數據的小工具,小輪子,和你們分享下 ~

這個工具不是什麼高大上的工具,是定義一個接口數據模型,該模型是面向人類和機器通用較友好的 API 文檔。

根據自定義的 schema 模型,構建業務返回的數據,功能包括:

  • 模型文件解析
  • 模型數據默認賦值
  • 規則校驗
  • ...(更多功能待挖掘,嘿嘿)

源碼地址: https://github.com/aydenuse/s...git

  1. 定義數據模型
{
    "title": "user", 
    "description": "用戶數據模型",
    "type": "object",
    "properties": {
        "id": {
            "type": "string",
            "dValue": ""
        },
        "name": {
            "type": "string",
            "dValue": ""
        },
        "age": {
            "type": "integer",
            "dValue": 0
        },
        "tall": {
            "type": "number",
            "dVallue": 0,
            "minimum": "1.40",
            "maximum": "3.00"
        },
        "status": {
            "type": "integer",
            "dValue": 0,
            "enumValue": [0, 1]
        },
        "tag": {
            "type": "array",
            "dValue": []
        },
        "students": {
            "type": "array",
            "dValue": [],
            "itemType": "object",
            "properties": {
                "name": {
                    "type": "string",
                    "dValue": ""
                }
            },
            "required": ["name"]
        },
        "music": {
            "type": "object",
            "dValue": {},
            "properties": {
                "id": {
                    "type": "string",
                    "dValue": ""
                },
                "duration": {
                    "type": "number",
                    "dValue": 0
                }
            },
            "required": ["id", "duration"]
        }
    },
    "required": ["id", "name", "age", "status", "music", "tag", "students", "tall"]
}
  1. 傳入要被解析的數據
'use strict'

// 模擬業務數據
const data = {
    id: '5gdv4r4sdadwqjdhhf43546',
    name: '我是王曉武',
    age: '23',
    tag: ['man', 'teacher', 'sport', { id: 1 }],
    _v: '123123',
    music: {

    },
    students: [
        {
            name: 'ayden'
        }
    ],
    tall: 1.89
}

const schemaParser = require('./schema-parser')
const schema = new schemaParser()
schema.init()

const result = schema.build({ data: data, title: 'user' })

console.log(result)
  1. result 被解析結果以下:
//
{
  id: '5gdv4r4sdadwqjdhhf43546',
  name: '我是王曉武',
  age: 23,
  status: 0,
  music: { id: '', duration: 0 },
  tag: [ 'man', 'teacher', 'sport', { id: 1 } ],
  students: [ { name: 'ayden' } ],
  tall: 1.89
}
相關文章
相關標籤/搜索