Skip to main content

getting-started

๐Ÿš€ Getting Started with express-cargoโ€‹

This document provides a minimum configuration guide for quickly experiencing express-cargo in a TypeScript + Express environment. The examples are based on pnpm + Node.js 18 or later.


1. Requirementsโ€‹

  • Node.js 18 or later (LTS recommended)

Package Manager: npm | yarn | pnpm โ†’ This document uses pnpm.

Since express-cargo uses Decorator + Metadata, TypeScript is recommended.


2. Installing Node.jsโ€‹

Install the LTS version appropriate for your OS from the official website below.

Verify installation:

node -v
pnpm -v

If successful, the version will be displayed.


3. Create a new project (pnpm)โ€‹

pnpmโ€‹

mkdir express-cargo-example
cd express-cargo-example
pnpm init

4. Set up the TypeScript environmentโ€‹

4-1. Install TypeScript and development dependenciesโ€‹

pnpm add -D typescript ts-node @types/node

4-2. Create tsconfig.jsonโ€‹

pnpm tsc --init
{
"compilerOptions": {
...,
"experimentalDecorators": true, // express-cargo required
"emitDecoratorMetadata": true, // use type metadata
...
},
...
}

โš ๏ธ experimentalDecorators, emitDecoratorMetadata Without it, validation/transformation in express-cargo will not work.


5. Install express & express-cargoโ€‹

pnpm add express express-cargo
pnpm add -D @types/express
pnpm add reflect-metadata

6. Base server + express-cargo settingsโ€‹

6-1. src/app.tsโ€‹

import express, { Request, Response, NextFunction } from 'express'
import { bindingCargo, getCargo, Body, Equal, CargoValidationError } from 'express-cargo'

const app = express()

const port = process.env.PORT || 3000

app.use(express.json())
app.use(express.urlencoded({ extended: true }))

class ExampleRequest {
@Body() // Extract fields from the request body
@Equal('1') // If the value is not "1", a validation error occurs
id!: string
}

app.post('/example', bindingCargo(ExampleRequest), (req, res) => { // bindingCargo(Class): Request โ†’ DTO conversion + validation
const cargo = getCargo<ExampleRequest>(req) // Return a validated type-safe object
res.json(cargo)
})

app.use((err: Error, req: Request, res: Response, next: NextFunction) => {
if (err instanceof CargoValidationError) {
res.status(400).json({
errors: err.errors.map(error => error.message),
})
return
}

next(err)
})

app.listen(port, () => {console.log(`Example app listening on port ${port}`)})

7. Runโ€‹

npm run dev

test request:

POST http://localhost:3000/example
Content-Type: application/json

{
"id": "1"
}

response:

{ "id": "1" }
  • โŒ "id": "2" โ†’ Validation Error occurs