Skip to content

Instantly share code, notes, and snippets.

@raphaelbadia
Created October 23, 2017 12:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save raphaelbadia/cf9c6572c8d77cf2b409ab72b0fe6711 to your computer and use it in GitHub Desktop.
Save raphaelbadia/cf9c6572c8d77cf2b409ab72b0fe6711 to your computer and use it in GitHub Desktop.
transform php-api returned json to classes
class Mother {
protected toInt = []
protected toBool = []
protected toObject = []
deserialize(instanceData) {
console.log('mother deserializing ')
const keys = Object.keys(this);
for (const key of keys) {
console.log(key)
if (instanceData.hasOwnProperty(key)) {
if (this.toInt.indexOf(key) !== -1)
this[key] = parseInt(instanceData[key])
else if (this.toBool.indexOf(key) !== -1)
this[key] = parseInt(instanceData[key]) !== 0
else {
console.log(key + ': ' + (typeof this[key]))
this[key] = instanceData[key];
}
}
}
}
}
export class Category extends Mother {
id: number = null
category_id: number = null
label: string = null
protected toInt = ['id', 'category_id']
constructor(instanceData) {
super()
this.deserialize(instanceData)
}
deserialize(instanceData) {
console.log('deserialize Category')
console.log('------- ')
console.log(instanceData)
super.deserialize(instanceData)
}
}
class Venue extends Mother {
public id: number = null
public mainCategory: Category = null
protected toInt = ['id']
constructor(instanceData) {
super()
this.deserialize(instanceData)
}
deserialize(instanceData) {
console.log('deserialize Venue')
console.log('------- ')
console.log(instanceData)
super.deserialize(instanceData)
this.mainCategory = new Category(instanceData.mainCategory)
}
}
class UserModel extends Mother {
public firstName: string = ""
public venues: Venue[] = []
public lastName: string = ""
public myBool: boolean = false
public myNumber: number = null
protected toInt = ['myNumber']
protected toBool = ['myBool']
constructor(instanceData) {
super()
this.deserialize(instanceData)
}
deserialize(instanceData) {
console.log('deserialize UserModel')
let data = instanceData
super.deserialize(instanceData)
this.venues = data.venues.map(v => new Venue(v))
console.log(data.venues)
}
}
let user = new UserModel({
firstName: "hello",
lastName: "world",
myBool: "1",
myNumber: "120",
venues: [
{
id: "1",
mainCategory: {
id: "12",
category_id: "42",
label: "cat1"
}
},
{
id: "2",
mainCategory: {
id: "21",
category_id: "24",
label: "cat2"
}
}],
})
console.log(user)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment