Skip to content

Typescript

nimda edited this page May 7, 2022 · 1 revision
import {Database, Indexed, PrimaryKey, Table} from '@n1md7/indexeddb-promise';

const app = document.querySelector<HTMLDivElement>('#app')!;

@Table({timestamps: true})
class User {
  @PrimaryKey({autoIncrement: true, unique: true})
  id: number;

  @Indexed({unique: true, multiEntry: false})
  username: string;

  @Indexed()
  password: string;

  toString() {
    return `#${this.id} ${this.username}`;
  }
}

@Table()
class Info {
  @PrimaryKey({autoIncrement: true, unique: true})
  id: number;

  @Indexed()
  userId: number;

  name: {
    first: string;
    last: string;
  };

  age: number;

  occupation: string;

  toString() {
    return `${this.name.first} ${this.name.last} ${this.age} years old - ${this.occupation}`;
  }
}

const store = new Database({
  version: 1,
  name: 'Store',
  tables: [User, Info],
});

await store.connect();

const userModel = store.useModel(User);
const infoModel = store.useModel(Info);

(async () => {
  const savedUser = await userModel.insert({
    username: 'admin',
    password: 'admin',
  })

  await infoModel.insert({
    userId: savedUser.id,
    name: {
      first: 'John',
      last: 'Doe',
    },
    age: 27,
    occupation: 'Web Developer',
  });
})().catch(console.log);

(async () => {

  const user = await userModel.selectByIndex('username', 'admin');
  if (!user) throw new Error('User not found');

  const info = await infoModel.select({where: {userId: user.id}});
  if (!info) throw new Error('Info not found');

  app.innerHTML = user.toString() + '<br>' + info.toString();
})().catch(console.log);
Clone this wiki locally