0.1.4Updated 6 months ago
import State from "@infinity-beyond/modules/state.ts";

export type MetaRow = {
  key: string,
  value_text: string | null,
  value_int: number | null,
  value_real: number | null,
  value_bool: boolean | null,
}

export class EntityMeta<
  EMC extends Entity.Meta.Config, 
  // deno-lint-ignore ban-types
  PEMC extends Entity.Meta.Config = {},
  ValidField = Extract<keyof EMC | keyof PEMC, string>
> {
  private table: string;
  private schema: EMC & PEMC;

  constructor(table: string, default_schema: EMC, passed_schema?: PEMC) {
    this.table = table;
    this.schema = { ...passed_schema, ...default_schema } as EMC & PEMC;
  }

  async get<Field extends ValidField, Value = Entity.Meta.InferFrom<EMC, PEMC, ValidField, Field>, Out = Field extends keyof EMC ? Value : Value | null>(field: Field): Promise<Out> {

    const { rows: [ row ] } = (await State.PostgresClient.query<MetaRow>(
      `SELECT * FROM ${this.table} WHERE key = $1 LIMIT 1`,
      [ field ]
    ));

    if(!row) return null as Out;

    switch(this.schema[row.key]) {
      case 'boolean': return row.value_bool as Out;
      case 'int': return row.value_int as Out;
      case 'real': return row.value_real as Out;
      default: return row.value_text as Out;
    }

  }

  async set<Field extends ValidField>(
    field: Field, 
    value: Entity.Meta.InferFrom<EMC, PEMC, ValidField, Field>
  ): Promise<Entity.Meta.InferFrom<EMC, PEMC, ValidField, Field>> {
    await State.PostgresClient.query(`UPDATE ${this.table} SET value=$2 WHERE key=$1`, [field, (value as Entity.Meta.Types | null)]);

    return value;
  }

  async increment<
    Field extends ExtractNumeric<EMC, PEMC, ValidField>
  >(field: Field, amount: number): Promise<number | null> {
    if (!['int', 'real'].includes(this.schema[field as keyof (EMC & PEMC)])) {
      throw new Error(`Field ${String(field)} is not a number type`);
    }

    const cast = this.schema[field];
    const { rows: [{ value } = {}] } = await State.PostgresClient.query<{ value: string }>(`UPDATE ${this.table} SET value = (value::${cast} + ${amount})::varchar WHERE key='${String(field)}' returning value`);

    if(!value) return null;

    if(cast == 'real') return parseFloat(value);
    return parseInt(value);
  }
}

type ExtractNumeric<EMC, PEMC, ValidField> =
  Extract<ValidField, {[F in keyof EMC]: EMC[F] extends 'int' ? F : EMC[F] extends 'real' ? F : never}[keyof EMC]> |
  Extract<ValidField, {[F in keyof PEMC]: PEMC[F] extends 'int' ? F : PEMC[F] extends 'real' ? F : never}[keyof PEMC]>;