Search code examples
postgresql.net-corehotchocolate

Dynamic graphql schema from json object


I am working on a multi-tenant SAAS application using efcore and graphql using hot chocolate as graphql server, where each tenant can define some custom fields/columns.

For instance, a tenant can add a column Email in customer entity, while another tenant can add another column like Phone in customer entity. On database side, the Customer table will have a pre-defined schema and an extra column named CustomFields. The CustomField column will have jsonb data-type (postgres database) and will store the extra columns added by tenant in json object.

Tenant1 -> Customer.CustomField {"Email": "[email protected]"}

Tenant2 -> Customer.CustomField {"Phone": "xxx-xxx-xxxx"}

The json document can contain any number of properties. My objective is to expose these properties as individual fields in GraphQL schema.

I reviewed extending-types, and tried to read the json document and dynamically create the new fields and append to Customer type. However, I can't make it work and dynamically add new dynamic properties as .

At this point not sure which of the following or any of these can be used

  1. Dynamic schema
  2. Schema Stiching
  3. Extended types.

Solution

  • I will answer here to my own question so that anyone else having a similar issue can possibly find a reference.

    The solution that worked for me is the Dynamic schema feature in version 13.

    Extended Types or Type extensions only allow adding/altering types statically during the schema building process. They will be helpful in scenarios like having more than one source for a schema and we want to stitch them without changing the definition of base object. But once a graphql schema is created, it's immutable.

    Dynamic types allow raising TypeChanged events to re-load or recreate schema and phase out the previous schema in a safe manner.

    Reference from Hot chocolate updated documentation https://chillicream.com/docs/hotchocolate/v13/defining-a-schema/dynamic-schemas