import { Cache, CacheAdapter } from 'ff-serv/cache'
import { Effect, Duration, Context } from 'effect'
import { HttpClient } from '@effect/platform'
class Database extends Context.Tag('Database')<
Database,
{ query: (sql: string) => Effect.Effect<unknown[]> }
>() {}
const program = Effect.gen(function* () {
const db = yield* Database
const userCache = yield* Cache.make({
ttl: Duration.minutes(5),
swr: Duration.minutes(5),
lookup: (userId: number) =>
Effect.gen(function* () {
yield* Effect.log(`Fetching user ${userId} from database`)
const rows = yield* db.query(`SELECT * FROM users WHERE id = ${userId}`)
return rows[0]
}),
adapter: CacheAdapter.memory({ capacity: 1000 }),
})
// First call: cache miss, fetches from DB
const user1 = yield* userCache.get(1)
yield* Effect.log('First call:', user1)
// Second call: cache hit, no DB query
const user2 = yield* userCache.get(1)
yield* Effect.log('Second call:', user2)
// Invalidate
yield* userCache.invalidate(1)
// Third call: cache miss again
const user3 = yield* userCache.get(1)
yield* Effect.log('Third call:', user3)
})
Effect.runPromise(
program.pipe(
Effect.provideService(Database, {
query: (sql) => Effect.succeed([{ id: 1, name: 'Alice' }]),
})
)
)