Skip to content

Instantly share code, notes, and snippets.

@octavioturra
Created August 24, 2016 03:57
Show Gist options
  • Save octavioturra/d5fc0ae35a5c552672b01fe39d4c459f to your computer and use it in GitHub Desktop.
Save octavioturra/d5fc0ae35a5c552672b01fe39d4c459f to your computer and use it in GitHub Desktop.

Validate data structure client-only

JWT

Generate the secret for the server; Uses secret to validate jwt with the structure;

If structure is valid, then, save data into the database;

Structure

Validatable contract:

 {
   fieldName: {
     type: <String, Number, Boolean, Array, Object>,
     nullable: Boolean,
     rule: /rege[xX]/,
     max: 3,
     min: 12,
     contract: {...}
   }
 }

Contract in package data:

btoa([
  [<type first letter>:fieldName],
])

Package exampe:

const contract = {
  name: {
    type: String,
    nullable: false,
  },
  age: {
    type: Number,
  },
  address: {
    type: Object,
    contract: {
      street: {
        type: String,
        number: String,
        zipCode: String,
      }
    }
  },
  telephones: {
    type: Array,
    contract: {
      ddd: {
        type: String,
      },
      phone: {
        type: String,
      }
    }
  },
  points: {
    type: Array,
    contract: Number,
  }
}

Rule to generate descriptor:

btoa(JSON.stringify({type: String.name, nullable: false, rule: /.{,3}/.source}))

Contract generate base function:

function transform(item) { 
    return Object
        .keys(item)
        .map(i => (({type, nullable, rule, max, min, contract}) => Object.entries({
            type: type.name, 
            nullable, 
            rule: rule && rule.source, 
            max, 
            min, 
            contract: contract && 
                      (type === Array) && (contract.name && contract.name || contract) || 
                      (type === Object) && transform(contract) ||
                      null, 
        })
        .filter(i => i[1])
        .reduce((o, v) => Object.assign(o, {[v[0]]: v[1]}), {}))(item[i])); 
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment