feathersjs / feathers

The API and real-time application framework
https://feathersjs.com
MIT License
14.97k stars 742 forks source link

Postgres jsonb best practice #3469

Closed EmileSpecs closed 2 months ago

EmileSpecs commented 2 months ago

Hi

It would seem like a common question but I can't find info on it anywhere!

I'm trying to figure out how best to handle JSONB column types in Postgres. Example schema:

export const permissionSchema = Type.Object(
  {
    id: Type.String({ format: 'uuid' }),
    name: Type.String(),
    description: Type.String(),
    rules: Type.Array(Type.Object({}), { default: [] })
  },
  { $id: 'Permission', additionalProperties: false }
)

If I create a permission here (using object array for rules), I of course get an error because the rules column must be converted to JSON string to save in Postgres.

If I convert the rules value to JSON string in a resolver, I will of course get a Typescript error (must be {}[]).

Is there a way to seamlessly convert to JSON string in the database adapter without changing the type of the column, since it will always be used as an object array in code? I tried overriding the database adapter create functions but that gives the same type errors, as the type is also used there.

I could do the inverse and type the column as string, but then I would have the same issues in the resolver by converting it to an object array.

Could someone please assist in how this is best handled? Is there a universal solution to convert all objects/arrays to JSON string to save in DB (except using feathers-objection which does this automatically)? Thanks!