Object Schema

Reviving regular objects

The structure of the object schema is the following

interface RevivalObjectSchema<T> {
  type: ReviveConstructor<T>;
  properties: { [key: string]: RevivalSchema<any> }
}

Member

Description

type

Model constructor (class or function)

properties

Map of properties and associated schemas which can be in turn simple constructors or complex schemas

Example:

const serialized = `{ "name": "John Smith", "job": { "title": "developer" } }`

/* Job model */
class Job {
  title = ''
  public getTitle() {
    return this.title
  }
}

/* Person model */
class Person {
  name = ''
  job: Job | null = null
  public getName() {
    return this.name
  }
  public getJob() {
    return this.job
  }
}

const schema: RevivalSchema<Person> = {
  type: Person,
  properties: {
    job: Job,
  },
}
const person = revive(serialized, schema)
console.log(person.getName()) // John Smith
console.log(person.getJob().getTitle()) // developer

In the above example, the job property maps out directly to a constructor.

Not all object properties need to be mapped through the schema. Note in the example above how we only map the jobproperty since it needs its own schema. The name is derived from the Person model itself.

An even more complex schema, where job maps out to an inner schema, can be the following:

Last updated

Was this helpful?