-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb.ts
More file actions
31 lines (27 loc) · 1012 Bytes
/
db.ts
File metadata and controls
31 lines (27 loc) · 1012 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import { ZenStackClient } from '@zenstackhq/orm';
import { SqlJsDialect } from '@zenstackhq/orm/dialects/sql.js';
import { sql } from '@zenstackhq/orm/helpers';
import initSqlJs from 'sql.js';
import { schema } from './zenstack/schema';
export async function createClient() {
// initialize sql.js engine
const SQL = await initSqlJs();
// create database client with sql.js dialect
const db = new ZenStackClient(schema, {
dialect: new SqlJsDialect({ sqlJs: new SQL.Database() }),
computedFields: {
User: {
// equivalent SQL:
// `(SELECT COUNT(*) AS "count" FROM "Post" WHERE "Post"."authorId" = "User"."id")
postCount: (eb, { modelAlias }) =>
eb.selectFrom('Post')
.whereRef('Post.authorId', '=', sql.ref(`${modelAlias}.id`))
.select(({fn}) => fn.countAll<number>().as('count'))
}
}
});
// push schema to the database
// the `$pushSchema` API is for testing purposes only
await db.$pushSchema();
return db;
}