2022-09-06 15:00:28 -04:00
|
|
|
making a basic API in deno
|
|
|
|
https://blog.logrocket.com/creating-your-first-rest-api-with-deno-and-postgres/
|
2023-08-23 09:40:21 -04:00
|
|
|
|
|
|
|
install deno:
|
|
|
|
curl -fsSL https://deno.land/x/install/install.sh | sh
|
|
|
|
|
|
|
|
a basic api:
|
|
|
|
```
|
|
|
|
import { Application, Router } from 'https://deno.land/x/oak/mod.ts';
|
|
|
|
import { Client } from "https://deno.land/x/postgres@v0.17.0/mod.ts";
|
|
|
|
|
|
|
|
const app = new Application();
|
|
|
|
const router = new Router();
|
|
|
|
|
|
|
|
// Configure database connection
|
|
|
|
const client = new Client({
|
|
|
|
hostname: 'usmidsap02',
|
|
|
|
port: 5432,
|
|
|
|
user: 'api',
|
|
|
|
password: '',
|
|
|
|
database: 'ubm',
|
|
|
|
});
|
|
|
|
|
|
|
|
await client.connect();
|
|
|
|
|
|
|
|
// Define a route to retrieve values from the database
|
|
|
|
router.get('/', async (ctx) => {
|
|
|
|
ctx.response.body = "live";
|
|
|
|
});
|
|
|
|
// Define a route to retrieve values from the database
|
|
|
|
router.get('/api/data', async (ctx) => {
|
|
|
|
const result = await client.queryObject("SELECT * FROM rlarp.pl LIMIT 10");
|
|
|
|
console.log(result.rows); // [{id: 1, name: 'Carlos'}, {id: 2, name: 'Johnru'}, ...]
|
|
|
|
//const result = await client.query('SELECT 1');
|
|
|
|
ctx.response.body = result.rows;
|
|
|
|
});
|
|
|
|
|
|
|
|
app.use(router.routes());
|
|
|
|
app.use(router.allowedMethods());
|
|
|
|
|
|
|
|
// Start the server
|
|
|
|
console.log('Server is running on http://localhost:8085');
|
|
|
|
await app.listen({ port: 8085 });
|
|
|
|
|
|
|
|
```
|