Recursive Schemas

In this section you'll find out how to design recursive revive schemas using revive schema providers

Recursive schemas are useful when modeling objects that have references to other instances of themselves. For example:

class Person {
    name = ''
    friends: Person[] = []
}

In this example, a Person has friends which are in turn Person objects.

Given the recursive dependency, it is impossible to revive such an object by describing a literal schema. Instead, we can rely on Schema Providers . We can turn the above class into a schema provider like this:

class Person {
    name = ''
    friends: Person[] = []
    
     public getRevivalSchema(): RevivalSchema<Person> {
       return {
         type: Person,
         properties: {
           friends: {
             items: Person
           }
         }
       }
     } 
}

Any class, not just the one associated with the object, can be a schema provider i.e.

class Person { /* ... */ }
class SchemaProvider {
  /* ... */
}

/* and then, revive using that class instead of Person - we will still 
get a Person object */
const person = revive(json, SchemaProvider)

Last updated

Was this helpful?