tywalch/electrodb

Get EntityType from Schema, not Entity

Closed this issue · 3 comments

With my current code I can get the UserType with EntityItem<typeof users>. My question is how can I get UserType from userSchema? My use case is I'd like to put userSchema and UserType into a common package so I can share the UserType between backend and frontend code. Thanks!

import { Entity, EntityItem, Schema } from "electrodb";

const userSchema: Schema<string, string, string> =  {
    model: {
      entity: "user",
      version: "1",
      service: "main",
    },
    attributes: {
      userId: {
        type: "string",
        readOnly: true,
        required: true,
      },
      email: {
        type: "string",
        required: true,
      },
      firstName: {
        type: "string",
        required: true,
      },
      lastName: {
        type: "string",
        required: true,
      },
      createdDate: {
        type: "string",
        default: () => new Date().toISOString(),
        readOnly: true,
      },
      updatedDate: {
        type: "string",
        readOnly: true,
        set: () => new Date().toISOString(),
        watch: "*",
      },
    },
    indexes: {
      primary: {
        pk: {
          field: "pk",
          composite: [],
        },
        sk: {
          field: "sk",
          composite: [],
        },
      },
    },
  };

const users = new Entity(userSchema, entityConfig);

type UserType = EntityItem<typeof users>;

I'll see what I can shake out here. Note that the type defined by Electro expects the schema to be readonly so that its attribute and index properties don't get widened to be just "string" values.

Just curious, could you go into your use-case for separating your schema definition? Knowing how folks use the library definitely impacts future development

@tywalch, thanks! My use case is so I can share the UserType between backend and frontend code. I have a /common package where I'd like to export the interface of the UserType and I don't want to have to have the client or table defined in /common. Make sense?

This issue is resolved with now having the ability to not specify entity configuration (second param) until after entity instantiation. See here for example.

I'd still like to request a helper type to extract EntityType from schema object (with as const). I'll create another issue for that. Thanks, @tywalch!