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:

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

/* JobProperties model */
class JobProperties {
  prop1 = ''
  getProp1() { return this.prop1 }

}

/* Job model */
class Job {
  title = ''
  props: JobProperties | null = null
  public getTitle() {
    return this.title
  }

  public getProps() { return this.props }
}

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

const schema: RevivalSchema<Employee> = {
  type: Employee,
  properties: {
    job: {
      type: Job,
      properties: {
        props: JobProperties
      }
    }
  },
}
const employee = revive(serialized, schema)
console.log(employee.getName()) // John Smith
console.log(employee.getJob().getTitle()) // developer
console.log(employee.getJob().getProps().getProp1()) // foobar

Last updated

Was this helpful?