Effect CommunityEC
Effect Community•3y ago•
6 replies
sparrovv

Ensuring Closure of DB Client in Program Workflow

Hey all 👋

I have a program that needs to write to a DB.
The DB client is passed as a layer.
How can I ensure that the client is closed when the workflow finish?

I looked into resource management, but it's not clear to me how to use it with layers 🤔

interface AwesomeDbClient {
  write: (key: string, value: string) => Promise<void>
  close: () => Promise<void>
}
type DBArgs = S.To<typeof DBArgs>
const DBArgs = S.struct({
  host: S.string,
})

export const DBClient = Context.Tag<AwesomeDbClient>()

export const makeDbClient = (args: DBArgs) => {
  const client = {
    write: (key: string, value: any) => {
      console.log(`writing ${key} ${value} to ${args.host}`)
      return Promise.resolve()
    },
    close: () => {
      console.log(`closing connection to ${args.host}`)
      return Promise.resolve()
    }
  }
  // client.connect()
  return Effect.succeed(client)
}

const clientLive = makeDbClient({ host: 'localhost' })
const writeToDb = (client: AwesomeDbClient, key: string, data: any) => {
  client.write(key, data)
}

const program = DBClient.pipe(
  Effect.flatMap((client) =>
    Effect.tryPromise(async () => {
      return writeToDb(client, "foo", { bar: 'data' })
    }),
  ),
  Effect.provideLayer(Layer.effect(DBClient, clientLive))
)

Effect.runPromise(program).then(() => console.log('done'))
Was this page helpful?