How to use Postgres Pool and attach it to context.state? #305
Answered
by
kitsonk
halvardssm
asked this question in
Q&A
-
Hi! I am trying to create an api with Oak and Postgres, but I am having some troubles passing the pool around as it doesn't seem to exist when I reference it in my routes. What would be a proper way of doing such? Here are my code snippets: // mod.ts
import { Application, State } from "https://deno.land/x/oak@v7.3.0/mod.ts";
import { Pool } from "https://deno.land/x/postgres@v0.11.2/mod.ts";
import { router } from "./router.ts";
const pool = new Pool(config, 10);
const app = new Application({ state: { pool } });
app.use(router.routes());
app.use(router.allowedMethods());
await app.listen({ port: 8000 }); // router.ts
import { Router } from "https://deno.land/x/oak@v7.3.0/mod.ts";
const router = new Router();
router.post("/test", async (ctx)=>{
const body = await ctx.request.body({ type: "json" }).value;
const client = await ctx.state.pool.connect();
const result = await client.queryArray`select 1`;
client.release();
ctx.response.body = result.rows
})
export {router} |
Beta Was this translation helpful? Give feedback.
Answered by
kitsonk
May 3, 2021
Replies: 1 comment 6 replies
-
The Because |
Beta Was this translation helpful? Give feedback.
6 replies
Answer selected by
halvardssm
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The
ctx.state
is a clone ofctx.app.state
that is created for each request/response interaction.Because
.pool
is intended to be "global" and exist for the lifetime of the application, I would try to usectx.app.state.pool
and see if that resolves the issue.