@@ -3,8 +3,10 @@ import pg from 'pg';
3
3
import format from 'pg-format' ;
4
4
import { v4 as uuid } from 'uuid' ;
5
5
import {
6
+ type DocumentHandler ,
6
7
type PongoCollection ,
7
8
type PongoDeleteResult ,
9
+ type PongoDocument ,
8
10
type PongoFilter ,
9
11
type PongoInsertManyResult ,
10
12
type PongoInsertOneResult ,
@@ -16,7 +18,7 @@ import {
16
18
import { constructFilterQuery } from './filter' ;
17
19
import { buildUpdateQuery } from './update' ;
18
20
19
- export const postgresCollection = < T > (
21
+ export const postgresCollection = < T extends PongoDocument > (
20
22
collectionName : string ,
21
23
{
22
24
dbName,
@@ -117,6 +119,24 @@ export const postgresCollection = <T>(
117
119
const result = await execute ( SqlFor . findOne ( filter ) ) ;
118
120
return ( result . rows [ 0 ] ?. data ?? null ) as T | null ;
119
121
} ,
122
+ handle : async (
123
+ id : string ,
124
+ handle : DocumentHandler < T > ,
125
+ ) : Promise < T | null > => {
126
+ await createCollection ;
127
+
128
+ const byId : PongoFilter < T > = { _id : id } ;
129
+
130
+ const existing = await collection . findOne ( byId ) ;
131
+
132
+ const result = await handle ( existing ) ;
133
+
134
+ if ( ! existing && result ) await collection . insertOne ( result ) ;
135
+ else if ( existing && result ) await collection . replaceOne ( byId , result ) ;
136
+ else if ( existing && ! result ) await collection . deleteOne ( byId ) ;
137
+
138
+ return result ;
139
+ } ,
120
140
find : async ( filter : PongoFilter < T > ) : Promise < T [ ] > => {
121
141
await createCollection ;
122
142
@@ -133,12 +153,12 @@ export const postgresCollection = <T>(
133
153
} ,
134
154
drop : async ( ) : Promise < boolean > => {
135
155
await createCollection ;
136
- const result = await execute ( SqlFor . dropCollection ( ) ) ;
156
+ const result = await execute ( SqlFor . drop ( ) ) ;
137
157
return ( result ?. rowCount ?? 0 ) > 0 ;
138
158
} ,
139
159
rename : async ( newName : string ) : Promise < PongoCollection < T > > => {
140
160
await createCollection ;
141
- await execute ( SqlFor . renameCollection ( newName ) ) ;
161
+ await execute ( SqlFor . rename ( newName ) ) ;
142
162
collectionName = newName ;
143
163
return collection ;
144
164
} ,
@@ -231,8 +251,8 @@ export const collectionSQLBuilder = (collectionName: string) => ({
231
251
filterQuery ,
232
252
) ;
233
253
} ,
234
- renameCollection : ( newName : string ) : SQL =>
254
+ rename : ( newName : string ) : SQL =>
235
255
sql ( 'ALTER TABLE %I RENAME TO %I' , collectionName , newName ) ,
236
- dropCollection : ( targetName : string = collectionName ) : SQL =>
256
+ drop : ( targetName : string = collectionName ) : SQL =>
237
257
sql ( 'DROP TABLE IF EXISTS %I' , targetName ) ,
238
258
} ) ;
0 commit comments