coerce.def 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. {{## def.coerceType:
  2. {{
  3. var $dataType = 'dataType' + $lvl
  4. , $coerced = 'coerced' + $lvl;
  5. }}
  6. var {{=$dataType}} = typeof {{=$data}};
  7. var {{=$coerced}} = undefined;
  8. {{? it.opts.coerceTypes == 'array' }}
  9. if ({{=$dataType}} == 'object' && Array.isArray({{=$data}}) && {{=$data}}.length == 1) {
  10. {{=$data}} = {{=$data}}[0];
  11. {{=$dataType}} = typeof {{=$data}};
  12. if ({{=it.util.checkDataType(it.schema.type, $data, it.opts.strictNumbers)}}) {{=$coerced}} = {{=$data}};
  13. }
  14. {{?}}
  15. if ({{=$coerced}} !== undefined) ;
  16. {{~ $coerceToTypes:$type:$i }}
  17. {{? $type == 'string' }}
  18. else if ({{=$dataType}} == 'number' || {{=$dataType}} == 'boolean')
  19. {{=$coerced}} = '' + {{=$data}};
  20. else if ({{=$data}} === null) {{=$coerced}} = '';
  21. {{?? $type == 'number' || $type == 'integer' }}
  22. else if ({{=$dataType}} == 'boolean' || {{=$data}} === null
  23. || ({{=$dataType}} == 'string' && {{=$data}} && {{=$data}} == +{{=$data}}
  24. {{? $type == 'integer' }} && !({{=$data}} % 1){{?}}))
  25. {{=$coerced}} = +{{=$data}};
  26. {{?? $type == 'boolean' }}
  27. else if ({{=$data}} === 'false' || {{=$data}} === 0 || {{=$data}} === null)
  28. {{=$coerced}} = false;
  29. else if ({{=$data}} === 'true' || {{=$data}} === 1)
  30. {{=$coerced}} = true;
  31. {{?? $type == 'null' }}
  32. else if ({{=$data}} === '' || {{=$data}} === 0 || {{=$data}} === false)
  33. {{=$coerced}} = null;
  34. {{?? it.opts.coerceTypes == 'array' && $type == 'array' }}
  35. else if ({{=$dataType}} == 'string' || {{=$dataType}} == 'number' || {{=$dataType}} == 'boolean' || {{=$data}} == null)
  36. {{=$coerced}} = [{{=$data}}];
  37. {{?}}
  38. {{~}}
  39. else {
  40. {{# def.error:'type' }}
  41. }
  42. if ({{=$coerced}} !== undefined) {
  43. {{# def.setParentData }}
  44. {{=$data}} = {{=$coerced}};
  45. {{? !$dataLvl }}if ({{=$parentData}} !== undefined){{?}}
  46. {{=$parentData}}[{{=$parentDataProperty}}] = {{=$coerced}};
  47. }
  48. #}}