MENU

express の基本を理解する

目次

  • expressとは何か?ポイントだけ抑える
  • DB接続 with Prisma
  • その他 expressのコード読むときに知っておきたいこと

expressとは何か?

expressjs.com

「Express は、それ自体では最小限の機能を備えたルーティングとミドルウェアの Web フレームワークです。」

とドキュメントに書いてあり、実際に触ってみて、ルーティングと、ミドルウェアの理解ができれば、実務でのコードもある程度読めるようになる気がしました。

ミドルウェアの理解

できることは下記らしい

  • 任意のコードを実行する。
  • リクエストオブジェクトとレスポンスオブジェクトを変更する。
  • リクエストレスポンスサイクルを終了する。
  • スタック内の次のミドルウェア関数を呼び出す。

任意のコードを実行する

app.useを利用して、下記のコードをリクエストがあるたびに実行する use() 関数と next() が大事だったはず

  • 下記は全体に適応させるケース
const app = express()

app.use((req, res, next) => {
  console.log('Time:', Date.now())
  next()
})
  • パス指定して適応させるケース

user/:id のリクエストのケースに限定させる時に

app.use('/user/:id', (req, res, next) => {
  console.log('Request Type:', req.method)
  next()
})

認証情報をチェックしたい時は下記のようなコードにする感じなのかも reqのヘッダー情報に headersでアクセスできる様子

const app = express()
const router = express.Router()

// predicate the router with a check and bail out when needed
router.use((req, res, next) => {
  if (!req.headers['x-auth']) return next('router')
  next()
})

router.get('/', (req, res) => {
  res.send('hello, user!')
})

// use the router and 401 anything falling through
app.use('/admin', router, (req, res) => {
  res.sendStatus(401)
})

クッキーパーサーは下記のように使ったことがあったな

const express = require('express')
const app = express()
const cookieParser = require('cookie-parser')

// load the cookie-parsing middleware
app.use(cookieParser())

DB接続をPrismaで行う方法

### ライブラリを入れる
yarn add prisma prisma/clientrst

### 初期ファイル作成
yarn prisma init

### .envファイルに DB接続先をかく

DATABASE_URL="postgresql://postgres:password@localhost:5433/todo-db?schema=public"

### schema.prisma にモデルをかく

model Todo {
  id              Int       @id @default(autoincrement())
  title           String?   @db.VarChar
  created_at      DateTime  @default(now())
  updated_at      DateTime  @default(now())
  deleted_at      DateTime?
}

### migrateをする

npx prisma migrate dev --name create_todo_table


### 接続

const { PrismaClient } = require('@prisma/client');

module.exports = (router) => {
  router.get('/hello', async (req, res) => {
    const prisma = new PrismaClient();
    const todos = await prisma.todo.findMany();
    console.log(`partners ${JSON.stringify(todos)}`)
    res.send('hello world')
  })
}

その他 理解

  • common jsの書き方

require (importではなく)

### export 元

module.exports = (router) => {
  router.get('/hoge', (req, res) => {
    res.send('hoge world')
  })
}

### import 先

const HelloRoute = require('./hello')