11import { ZenStackClient } from '../../dist' ;
22import { schema } from './schema' ;
33
4- const client = new ZenStackClient ( schema ) ;
4+ const client = new ZenStackClient ( schema , {
5+ computedFields : {
6+ User : {
7+ postCount : ( eb ) =>
8+ eb
9+ . selectFrom ( 'Post' )
10+ . whereRef ( 'Post.authorId' , '=' , 'User.id' )
11+ . select ( ( { fn } ) => fn . countAll < number > ( ) . as ( 'postCount' ) ) ,
12+ } ,
13+ } ,
14+ } ) ;
515
616async function main ( ) {
717 await find ( ) ;
@@ -11,6 +21,7 @@ async function main() {
1121 await count ( ) ;
1222 await aggregate ( ) ;
1323 await groupBy ( ) ;
24+ await queryBuilder ( ) ;
1425}
1526
1627async function find ( ) {
@@ -20,16 +31,19 @@ async function find() {
2031 } ,
2132 } ) ;
2233 console . log ( user1 ?. name ) ;
34+ console . log ( user1 ?. postCount ) ;
2335
2436 const users = await client . user . findMany ( {
2537 include : { posts : true } ,
26- omit : { email : true } ,
38+ omit : { email : true , postCount : true } ,
2739 } ) ;
2840 console . log ( users . length ) ;
2941 console . log ( users [ 0 ] ?. name ) ;
3042 console . log ( users [ 0 ] ?. posts . length ) ;
3143 // @ts -expect-error
3244 console . log ( users [ 0 ] ?. email ) ;
45+ // @ts -expect-error
46+ console . log ( users [ 0 ] ?. postCount ) ;
3347
3448 // @ts -expect-error select/omit are not allowed together
3549 await client . user . findMany ( {
@@ -44,7 +58,7 @@ async function find() {
4458 } ) ;
4559
4660 const user2 = await client . user . findUniqueOrThrow ( {
47- where :
{ email :
'[email protected] ' } , 61+ where :
{ email :
'[email protected] ' , postCount : { gt : 0 } } , 4862 select : { email : true , profile : true } ,
4963 } ) ;
5064 console . log ( user2 . email ) ;
@@ -532,4 +546,16 @@ async function groupBy() {
532546 console . log ( r [ 0 ] ?. age ) ;
533547}
534548
549+ async function queryBuilder ( ) {
550+ const r = await client . $qb
551+ . selectFrom ( 'User' )
552+ . where ( 'name' , '=' , 'Alex' )
553+ . select ( [ 'id' , 'email' ] )
554+ . executeTakeFirstOrThrow ( ) ;
555+ console . log ( r . id ) ;
556+ console . log ( r . email ) ;
557+ // @ts -expect-error
558+ console . log ( r . name ) ;
559+ }
560+
535561main ( ) ;
0 commit comments