vigetlabs / microcosm

Flux with actions at center stage. Write optimistic updates, cancel requests, and track changes with ease.
http://code.viget.com/microcosm/
MIT License
487 stars 22 forks source link

[micromanage] Add schemas #489

Closed nhunzaker closed 6 years ago

nhunzaker commented 6 years ago

This commit adds an initial draft of schemas. If an entity is created without a schema, it fails. Additionally, if a property does not match the schema, it fails. Essentially:

class Planet extends Entity {
  static schema = {
    name: String
  }
}

let earth = new Planet({ name: 'earth' })
let invalid = new Planet({ name: 2 })
 // Raises exception:
// 'Entity "Planet" expected a String for key "name". Instead found Number.'

Is this too strict?

I like the strictness, but I also know that it would be a bummer for an API to change a string or number field, or decide to return null. I still need to figure out the best approach for that.

One idea is to allow it, with an option to send warnings about schema mismatches in a backchannel. You'd get an alert about the issue, but a user wouldn't see an error.

Will this hold up?

This is probably okay for numbers, strings, and booleans. What about dates?

Instead, we could use JSON schemas:

class Planet extends Entity {
  static schema = {
    required: [ "name"],
    name: {
      type: "string",
      description: "name of planet; required."
    }
  }
}

Long term, I can see nice interop with React components that generate forms based on schemas:

Or documentation generation:

codecov-io commented 6 years ago

Codecov Report

Merging #489 into master will not change coverage. The diff coverage is n/a.

Impacted file tree graph

@@          Coverage Diff          @@
##           master   #489   +/-   ##
=====================================
  Coverage      98%    98%           
=====================================
  Files          29     29           
  Lines         702    702           
  Branches      137    137           
=====================================
  Hits          688    688           
  Misses         12     12           
  Partials        2      2

Continue to review full report at Codecov.

Legend - Click here to learn more Δ = absolute <relative> (impact), ø = not affected, ? = missing data Powered by Codecov. Last update c1d0c84...104298b. Read the comment docs.

efatsi commented 6 years ago

Kewl

nhunzaker commented 6 years ago

Thanks, @efatsi!