-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdb-instance-legacy-mongo-client.ts
59 lines (48 loc) · 1.62 KB
/
db-instance-legacy-mongo-client.ts
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import * as DbInstance from "@effect-mongodb/services/DbInstance"
import * as DbService from "@effect-mongodb/services/DbService"
import * as Collection from "effect-mongodb/Collection"
import * as Db from "effect-mongodb/Db"
import * as FindCursor from "effect-mongodb/FindCursor"
import * as Effect from "effect/Effect"
import * as Schema from "effect/Schema"
import { MongoClient } from "mongodb"
const Todo = Schema.Struct({
userId: Schema.Number,
id: Schema.Number,
title: Schema.String,
completed: Schema.Boolean
})
const MyDb = DbService.Tag("MyDb")
const program = Effect.gen(function*() {
const db = yield* MyDb
const sourceCollection = Db.collection(db, "source", Todo)
const destinationCollection = Db.collection(db, "destination", Todo)
const items = yield* Collection.find(sourceCollection).pipe(FindCursor.toArray)
yield* Collection.insertMany(destinationCollection, items)
})
/*** main.ts ***/
class LegacyConnectionPool {
private static instance: MongoClient | null = null
static async mongoClient(url: string) {
if (!this.instance) {
this.instance = new MongoClient(url)
await this.instance.connect()
}
return this.instance
}
static async close() {
if (!this.instance) return
await this.instance.close()
}
}
const MyDbLive = DbInstance.fromMongoClient(
MyDb,
Effect.gen(function*() {
const client = yield* Effect.promise(() => LegacyConnectionPool.mongoClient("mongodb://localhost:27017"))
return { database: { name: "mydb" }, client }
})
)
await program.pipe(
Effect.provide(MyDbLive),
Effect.runPromise
).then(() => LegacyConnectionPool.close())