我想用
Normalizr
到
flatten
红州。下面是模式定义
import { normalize, schema } from 'normalizr'
const fooSchema = new schema.Entity('foos')
const barSchema = new schema.Entity('bars')
const fooMemberSchema = new schema.Entity('fooMembers', {
foo: fooSchema
})
const barMemberSchema = new schema.Entity('barMembers', {
bar: barSchema
})
export { fooSchema, barSchema, fooMemberSchema, barMemberSchema }
这是给
normalize
在
doGet
功能
import axios from 'axios'
import { normalize } from 'normalizr'
import { Promise } from 'es6-promise'
import querystring from 'querystring'
import { CONTEXT_PATH, API_PATH } from '../properties/Properties'
import { fooSchema, barSchema, fooMemberSchema, barMemberSchema } from '../stores/Schema'
/**
* Tuomas Toivonen
* 13.1.2019
*/
// Backend mock for development and debugging purposes
const Api = {
resources: {
foo: {},
bar: {}
},
doGet({ uri, config={} }) {
// TODO: tokenize uri
let data = Object.values(this.resources[uri])
console.log(data)
console.log(normalize(data, [fooSchema]))
return Promise.resolve({data: data})
},
doPost({ uri, entity, config={} }) {
let id = entity.id
if (!id) {
id = guid()
entity.id = id
}
this.resources[uri][id] = entity
return Promise.resolve({data: entity})
},
doPut({ uri, entity, config={} }) {
Promise.reject({message: "doPut not implemented"})
},
doDelete({ uri, entity, config={} }) {
Promise.reject({message: "doDelete Not implemented"})
}
}
// Generate dummy data
for (let i=0; i<3; i++) {
let fooId = guid()
let barId = guid()
Api.resources.foo[fooId] = {
id: fooId,
value: `Foo ${i}`,
fooMembers: [
...(function*() {
for (let i=0; i<5; i++)
yield { id: guid(), value: `FooMember ${i}` }
})()
]
}
Api.resources.bar[barId] = {
id: barId,
value: `Bar ${i}`,
barMembers: [
...(function*() {
for (let i=0; i<5; i++)
yield { id: guid(), value: `BarMember ${i}` }
})()
]
}
}
console.log('Using mock API:')
console.log(Api)
function guid() {
function s4() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
}
return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4();
}
export default Api
然而,它并没有像预期的那样使结构正常化。以下是控制台日志消息:
规范化前的有效载荷:
标准化后的有效载荷:
出于某种原因,foombers仍然是嵌套的。为什么?