Comments
GitHub sign-in is not configured yet, so posting is temporarily unavailable.
- Loading...
This post adapts to your choices. Pick a server framework and watch the code animate between implementations.
First, create a new project and install dependencies:
mkdir my-api && cd my-apinpm init -ynpm i expressnpm i -D typescript tsx @types/express
Let's create a simple server that responds with "Hello world!":
import express from 'express'const app = express()app.get('/', (req, res) => {res.send('Hello world!')})const port = process.env.PORT || 3000app.listen(port, () => {console.log(`Express started on http://localhost:${port}`)})
Express is imported, then an instance is created and saved as app. The app.get() method registers a route handler for GET requests to /.
Now let's add a route that accepts a name parameter:
import express from 'express'const app = express()app.get('/', (req, res) => {res.send('Hello world!')})app.get('/:name', (req, res) => {res.send(`Hello ${req.params.name}!`)})const port = process.env.PORT || 3000app.listen(port, () => {console.log(`Express started on http://localhost:${port}`)})
Test it:
curl localhost:3000/foo
You should see "Hello foo!" regardless of which framework you chose.
Now let's add a database. We'll use PostgreSQL.
import { Kysely, PostgresDialect } from 'kysely'import type { DB } from 'kysely-codegen'import pg from 'pg'export const db = new Kysely<DB>({dialect: new PostgresDialect({pool: new pg.Pool({connectionString: process.env.DATABASE_URL,}),}),})
Kysely is a type-safe query builder. Combined with kysely-codegen, it introspects your database and generates TypeScript types that match your schema.
Now let's create functions to interact with a movies table:
import { db } from './db'export async function list() {return db.selectFrom('movies').selectAll().execute()}export async function create(title: string, released: number) {return db.insertInto('movies').values({ title, released }).returningAll().executeTakeFirstOrThrow()}
Finally, let's connect the routes to the database methods. This is where both choices come together:
import express from 'express'import * as movies from './movies'const app = express()app.use(express.json())app.get('/api/movies', async (req, res) => {res.json(await movies.list())})app.post('/api/movies', async (req, res) => {const { title, released } = req.bodyres.json(await movies.create(title, released))})const port = process.env.PORT || 3000app.listen(port, () => {console.log(`Express started on http://localhost:${port}`)})
Notice how the src/index.ts changes with your server choice, while src/movies.ts and src/db.ts change with your adapter choice — the two dimensions are independent!
GitHub sign-in is not configured yet, so posting is temporarily unavailable.