validator.js 8.2 KB
Newer Older
DCloud_JSON's avatar
DCloud_JSON 已提交
1 2 3 4 5 6 7 8
const {
  isValidString,
  getType
} = require('./utils.js')
const {
  ERROR
} = require('./error')

雪洛's avatar
雪洛 已提交
9
const baseValidator = Object.create(null)
DCloud_JSON's avatar
DCloud_JSON 已提交
10

雪洛's avatar
雪洛 已提交
11
baseValidator.username = function (username) {
DCloud_JSON's avatar
DCloud_JSON 已提交
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
  const errCode = ERROR.INVALID_USERNAME
  if (!isValidString(username)) {
    return {
      errCode
    }
  }
  if (/^\d+$/.test(username)) {
    // 用户名不能为纯数字
    return {
      errCode
    }
  };
  if (!/^[a-zA-Z0-9_-]+$/.test(username)) {
    // 用户名仅能使用数字、字母、“_”及“-”
    return {
      errCode
    }
  }
}

雪洛's avatar
雪洛 已提交
32
baseValidator.password = function (password) {
DCloud_JSON's avatar
DCloud_JSON 已提交
33 34 35 36 37 38 39 40 41 42 43 44 45 46
  const errCode = ERROR.INVALID_PASSWORD
  if (!isValidString(password)) {
    return {
      errCode
    }
  }
  if (password.length < 6) {
    // 密码长度不能小于6
    return {
      errCode
    }
  }
}

雪洛's avatar
雪洛 已提交
47
baseValidator.mobile = function (mobile) {
DCloud_JSON's avatar
DCloud_JSON 已提交
48 49 50 51 52 53 54 55 56 57 58 59 60
  const errCode = ERROR.INVALID_MOBILE
  if (!isValidString(mobile)) {
    return {
      errCode
    }
  }
  if (!/^1\d{10}$/.test(mobile)) {
    return {
      errCode
    }
  }
}

雪洛's avatar
雪洛 已提交
61
baseValidator.email = function (email) {
DCloud_JSON's avatar
DCloud_JSON 已提交
62 63 64 65 66 67 68 69 70 71 72 73 74
  const errCode = ERROR.INVALID_EMAIL
  if (!isValidString(email)) {
    return {
      errCode
    }
  }
  if (!/@/.test(email)) {
    return {
      errCode
    }
  }
}

雪洛's avatar
雪洛 已提交
75
baseValidator.nickname = function (nickname) {
DCloud_JSON's avatar
DCloud_JSON 已提交
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
  const errCode = ERROR.INVALID_NICKNAME
  if (nickname.indexOf('@') !== -1) {
    // 昵称不允许含@
    return {
      errCode
    }
  };
  if (/^\d+$/.test(nickname)) {
    // 昵称不能为纯数字
    return {
      errCode
    }
  };
  if (nickname.length > 100) {
    // 昵称不可超过100字符
    return {
      errCode
    }
  }
}

雪洛's avatar
雪洛 已提交
97 98 99 100 101 102 103
const baseType = ['string', 'boolean', 'number', 'null'] // undefined不会由客户端提交上来

baseType.forEach((type) => {
  baseValidator[type] = function (val) {
    if (getType(val) === type) {
      return
    }
DCloud_JSON's avatar
DCloud_JSON 已提交
104 105 106 107
    return {
      errCode: ERROR.INVALID_PARAM
    }
  }
雪洛's avatar
雪洛 已提交
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
})

function tokenize (name) {
  let i = 0
  const result = []
  let token = ''
  while (i < name.length) {
    const char = name[i]
    switch (char) {
      case '|':
      case '<':
      case '>':
        token && result.push(token)
        result.push(char)
        token = ''
        break
      default:
        token += char
        break
    }
    i++
    if (i === name.length && token) {
      result.push(token)
DCloud_JSON's avatar
DCloud_JSON 已提交
131 132
    }
  }
雪洛's avatar
雪洛 已提交
133
  return result
DCloud_JSON's avatar
DCloud_JSON 已提交
134 135
}

雪洛's avatar
雪洛 已提交
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
/**
 * 处理validator名
 * @param {string} name
 */
function parseValidatorName (name) {
  const tokenList = tokenize(name)
  let i = 0
  let currentToken = tokenList[i]
  const result = {
    type: 'root',
    children: [],
    parent: null
  }
  let lastRealm = result
  while (currentToken) {
    switch (currentToken) {
      case 'array': {
        const currentRealm = {
          type: 'array',
          children: [],
          parent: lastRealm
        }
        lastRealm.children.push(currentRealm)
        lastRealm = currentRealm
        break
雪洛's avatar
雪洛 已提交
161
      }
雪洛's avatar
雪洛 已提交
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
      case '<':
        if (lastRealm.type !== 'array') {
          throw new Error('Invalid validator token "<"')
        }
        break
      case '>':
        if (lastRealm.type !== 'array') {
          throw new Error('Invalid validator token ">"')
        }
        lastRealm = lastRealm.parent
        break
      case '|':
        if (lastRealm.type !== 'array' && lastRealm.type !== 'root') {
          throw new Error('Invalid validator token "|"')
        }
        break
      default:
        lastRealm.children.push({
          type: currentToken
        })
        break
DCloud_JSON's avatar
DCloud_JSON 已提交
183
    }
雪洛's avatar
雪洛 已提交
184 185
    i++
    currentToken = tokenList[i]
雪洛's avatar
雪洛 已提交
186
  }
雪洛's avatar
雪洛 已提交
187 188
  return result
}
雪洛's avatar
雪洛 已提交
189

雪洛's avatar
雪洛 已提交
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
function getRuleCategory (rule) {
  switch (rule.type) {
    case 'array':
      return 'array'
    case 'root':
      return 'root'
    default:
      return 'base'
  }
}

function isMatchUnionType (val, rule) {
  if (!rule.children || rule.children.length === 0) {
    return true
  }
  const children = rule.children
  for (let i = 0; i < children.length; i++) {
    const child = children[i]
    const category = getRuleCategory(child)
    let pass = false
    switch (category) {
      case 'base':
        pass = isMatchBaseType(val, child)
        break
      case 'array':
        pass = isMatchArrayType(val, child)
        break
      default:
        break
    }
    if (pass) {
      return true
DCloud_JSON's avatar
DCloud_JSON 已提交
222 223
    }
  }
雪洛's avatar
雪洛 已提交
224 225 226 227 228 229 230 231 232 233 234 235
  return false
}

function isMatchBaseType (val, rule) {
  if (typeof baseValidator[rule.type] !== 'function') {
    throw new Error(`invalid schema type: ${rule.type}`)
  }
  const validateRes = baseValidator[rule.type](val)
  if (validateRes && validateRes.errCode) {
    return false
  }
  return true
雪洛's avatar
雪洛 已提交
236
}
DCloud_JSON's avatar
DCloud_JSON 已提交
237

雪洛's avatar
雪洛 已提交
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279
function isMatchArrayType (arr, rule) {
  if (getType(arr) !== 'array') {
    return false
  }
  if (rule.children && rule.children.length && arr.some(item => !isMatchUnionType(item, rule))) {
    return false
  }
  return true
}

class Validator {
  constructor () {
    this.baseValidator = baseValidator
    this.customValidator = Object.create(null)
  }

  mixin (type, handler) {
    this.customValidator[type] = handler
  }

  getRealBaseValidator (type) {
    return this.customValidator[type] || this.baseValidator[type]
  }

  get validator () {
    return new Proxy({}, {
      get: (_, prop) => {
        if (typeof prop !== 'string') {
          return
        }
        const realBaseValidator = this.getRealBaseValidator(prop)
        if (realBaseValidator) {
          return realBaseValidator
        }
        const rule = parseValidatorName(prop)
        return function (val) {
          if (!isMatchUnionType(val, rule)) {
            return {
              errCode: ERROR.INVALID_PARAM
            }
          }
        }
DCloud_JSON's avatar
DCloud_JSON 已提交
280
      }
雪洛's avatar
雪洛 已提交
281 282 283 284 285 286 287 288 289 290
    })
  }

  validate (value = {}, schema = {}) {
    for (const schemaKey in schema) {
      let schemaValue = schema[schemaKey]
      if (getType(schemaValue) === 'string') {
        schemaValue = {
          required: true,
          type: schemaValue
DCloud_JSON's avatar
DCloud_JSON 已提交
291 292
        }
      }
雪洛's avatar
雪洛 已提交
293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
      const {
        required,
        type
      } = schemaValue
      // value内未传入了schemaKey或对应值为undefined
      if (value[schemaKey] === undefined) {
        if (required) {
          return {
            errCode: ERROR.PARAM_REQUIRED,
            errMsgValue: {
              param: schemaKey
            },
            schemaKey
          }
        } else {
          continue
        }
      }
      const validateMethod = this.validator[type]
      if (!validateMethod) {
        throw new Error(`invalid schema type: ${type}`)
      }
      const validateRes = validateMethod(value[schemaKey])
      if (validateRes) {
        validateRes.schemaKey = schemaKey
        return validateRes
      }
DCloud_JSON's avatar
DCloud_JSON 已提交
320 321 322 323
    }
  }
}

雪洛's avatar
雪洛 已提交
324
function checkClientInfo (clientInfo) {
325 326 327 328 329 330
  const stringNotRequired = {
    required: false,
    type: 'string'
  }
  const numberNotRequired = {
    required: false,
331
    type: 'number'
332
  }
雪洛's avatar
雪洛 已提交
333 334 335
  const schema = {
    uniPlatform: 'string',
    appId: 'string',
336 337 338 339 340 341 342
    deviceId: stringNotRequired,
    osName: stringNotRequired,
    locale: stringNotRequired,
    clientIP: stringNotRequired,
    appName: stringNotRequired,
    appVersion: stringNotRequired,
    appVersionCode: stringNotRequired,
雪洛's avatar
雪洛 已提交
343 344 345 346
    channel: {
      required: false,
      type: 'number|string'
    },
347 348 349 350 351 352 353 354 355 356 357 358 359 360
    userAgent: stringNotRequired,
    uniIdToken: stringNotRequired,
    deviceBrand: stringNotRequired,
    deviceModel: stringNotRequired,
    osVersion: stringNotRequired,
    osLanguage: stringNotRequired,
    osTheme: stringNotRequired,
    romName: stringNotRequired,
    romVersion: stringNotRequired,
    devicePixelRatio: numberNotRequired,
    windowWidth: numberNotRequired,
    windowHeight: numberNotRequired,
    screenWidth: numberNotRequired,
    screenHeight: numberNotRequired
雪洛's avatar
雪洛 已提交
361
  }
雪洛's avatar
雪洛 已提交
362
  const validateRes = new Validator().validate(clientInfo, schema)
雪洛's avatar
雪洛 已提交
363 364 365 366 367
  if (validateRes) {
    if (validateRes.errCode === ERROR.PARAM_REQUIRED) {
      console.warn('- 如果使用HBuilderX运行本地云函数/云对象功能时出现此提示,请改为使用客户端调用本地云函数方式调试,或更新HBuilderX到3.4.12及以上版本。\n- 如果是缺少clientInfo.appId,请检查项目manifest.json内是否配置了DCloud AppId')
      throw new Error(`"clientInfo.${validateRes.schemaKey}" is required.`)
    } else {
368
      throw new Error(`Invalid client info: clienInfo.${validateRes.schemaKey}`)
雪洛's avatar
雪洛 已提交
369 370 371 372
    }
  }
}

DCloud_JSON's avatar
DCloud_JSON 已提交
373
module.exports = {
雪洛's avatar
雪洛 已提交
374
  Validator,
雪洛's avatar
雪洛 已提交
375
  checkClientInfo
DCloud_JSON's avatar
DCloud_JSON 已提交
376
}