JS-DATA KEY TERMS
- Front End Model Layer
- RESTful Resources
- Framework-agnostic data store
- Relations
- Twitter Bootstrap for Front Data Modeling
- Schemata & Validation
- Custom Instance Behavior
- Promises
Front End Model Layers
- mongoose is to our database what front end model layers are to our RESTful endpoints
- Creating instances of a class: $http.get() vs Cohort.find()
//regular old data
$http.get()
// data that becomes an
//instance of a configured Class
Cohort.find()
//under the hood
return response.data.map(function(item){
return Cohort.createInstance(item)
})
angular.module('myApp')
.config(function(DSHttpAdapter){
// any call to the DB prepended by '/api'
DSHttpAdatperProvider.defaults.basePath = '/api'
})
.factory('Cohort', function(DS) {
// register our resource with the Data Store
var Cohort = DS.defineResource({
name: 'cohorts',
idAttribute: '_id'
})
return Cohort;
})
THE DS Object
- DS is a constructor function that creates instances of the registered resource definition
- Takes a configuration object and returns a resource
- DSHttpAdapter, DSFirebaseAdapter, etc
In Memory Cache
- DS not only turns our data into instances, it injects into an in-memory cache
var Cohort = DS.defineResource({
name: 'cohorts',
idAttribute: '_id'
})
Cohort.find()
.then(function(data){
return data.map(function(datum){
return Cohort.createInstance(datum)
})
})
.then(function(instances){
// inject your data into the in memory cache
// for retrieval at a later time
Cohort.inject(instances)
})
JS-DATA REST Assumptions
ASYNC: pinging your database
1. Cohort.findAll() --> GET '/api/cohorts/'
2. Cohort.find('1') -- > GET '/api/cohorts/1'
3. Cohort.create(data) --> POST '/api/cohorts/'
SYNC: modifying the data store
1. Cohort.getAll()
2. Cohort.get()
3. Cohort.inject(data)
var getCohorts = function(){
var cohortsArr;
// first check if there's anything in the cache
if (cohortsArr = Cohort.getAll()) return cohortsArr;
// if nothing in the cache, ping the database
else return Cohort.find()
}
// /api/workshops/:workshopId/concepts/:conceptId
.factory('Concept', function (DS) {
return DS.defineResource({
name: 'concepts',
idAttribute: '_id',
relations: {
hasMany: {
actions: {
foreignKey: 'concept',
localKey: '_id'
}
},
belongsTo: {
workshops: {
parent: true,
localKey: '_id',
localField: 'workshops'
}
}
}
});
RELATIONS