Node.js Foundations·Practice drills 3

Drill 6: Improve it — Databases with Postgres

Add one improvement and explain the benefit.

Intermediate 5 min read Lesson 63 of 300 Challenge included
What you will be able to do
  • Add one improvement and explain the benefit.

Practice task

Add one improvement and explain the benefit.

courses.tsTypeScript
import { Pool } from 'pg'

const pool = new Pool({
  connectionString: process.env.DATABASE_URL,
  max: 10,
})

type Course = {
  id: string
  title: string
  minutes: number
}

async function findCourse(id: string): Promise<Course | null> {
  const result = await pool.query<Course>(
    'select id, title, minutes from courses where id = $1',
    [id],
  )
  return result.rows[0] ?? null
}

async function createCourse(course: Course): Promise<Course> {
  const client = await pool.connect()
  try {
    await client.query('begin')
    await client.query(
      'insert into courses (id, title, minutes) values ($1, $2, $3)',
      [course.id, course.title, course.minutes],
    )
    await client.query('commit')
    return course
  } catch (error) {
    await client.query('rollback')
    throw error
  } finally {
    client.release()
  }
}
Your turn

Write your answer

Easy

Add one improvement and explain the benefit.

TEXT · starter
Your answer…
Study tools

Make it yours.

Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.

Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign in
Finished reading?

Lock in what you just learned.

Mark this lesson complete to save your place and move one step closer to the certificate.

Lesson 63 of 300 · 0% of course