import { createServer } from 'node:http'
import { fleet } from './fleet.js'
import { sendJson } from './respond.js'
const routes = {
'/health': {
GET: (req, res) => sendJson(res, 200, { status: 'ok' })
},
'/boats': {
GET: (req, res) => sendJson(res, 200, fleet)
}
}
export function handleRequest(req, res) {
const { pathname } = new URL(req.url, 'http://localhost')
const route = routes[pathname]
if (!route) {
return sendJson(res, 404, { error: { code: 'not_found', message: `Nothing lives at ${pathname}` } })
}
const handler = route[req.method]
if (!handler) {
const allowed = Object.keys(route).join(', ')
res.setHeader('allow', allowed)
return sendJson(res, 405, {
error: { code: 'method_not_allowed', message: `${pathname} accepts ${allowed}` }
})
}
handler(req, res)
}
export function createApp() {
return createServer((req, res) => {
try {
handleRequest(req, res)
} catch (err) {
res.statusCode = 500
res.end(`Server error: ${err.message}\n`)
}
})
}
import { BOAT_TYPES } from './boats.js'
import { HttpError } from './errors.js'
const SORT_FIELDS = ['code', 'name', 'hourlyCents']
function wholeNumber(text, min, max) {
if (!/^\d+$/.test(text)) return null
const n = Number(text)
return n >= min && n <= max ? n : null
}
export function parseListQuery(searchParams) {
const query = { type: null, available: null, sortBy: 'code', order: 'asc', limit: 10, offset: 0 }
const details = []
const bad = (field, message) => details.push({ field, message })
const type = searchParams.get('type')
if (type !== null) {
if (BOAT_TYPES.includes(type)) query.type = type
else bad('type', `must be one of ${BOAT_TYPES.join(', ')}`)
}
const available = searchParams.get('available')
if (available !== null) {
if (available === 'true' || available === 'false') query.available = available === 'true'
else bad('available', 'must be true or false')
}
const sort = searchParams.get('sort')
if (sort !== null) {
const desc = sort.startsWith('-')
const field = desc ? sort.slice(1) : sort
if (SORT_FIELDS.includes(field)) {
query.sortBy = field
query.order = desc ? 'desc' : 'asc'
} else {
bad('sort', `must be one of ${SORT_FIELDS.join(', ')}, optionally starting with -`)
}
}
const limit = searchParams.get('limit')
if (limit !== null) {
query.limit = wholeNumber(limit, 1, 50)
if (query.limit === null) bad('limit', 'must be a whole number from 1 to 50')
}
const offset = searchParams.get('offset')
if (offset !== null) {
query.offset = wholeNumber(offset, 0, Number.MAX_SAFE_INTEGER)
if (query.offset === null) bad('offset', 'must be a whole number from 0')
}
if (details.length > 0) {
import { createServer } from 'node:http'
import { readJson } from './body.js'
import { validateBoat } from './boats.js'
import { HttpError } from './errors.js'
import { fleet } from './fleet.js'
import { priceQuote, validateQuote } from './quote.js'
import { sendJson } from './respond.js'
import { createBoatStore } from './store.js'
function listBoats(req, res, { store }) {
sendJson(res, 200, store.list())
}
function boatNotFound(code) {
return new HttpError(404, 'not_found', `No boat with code ${code}`)
}
function getBoat(req, res, { store, params }) {
const boat = store.get(params.code)
if (!boat) throw boatNotFound(params.code)
sendJson(res, 200, boat)
}
async function createBoat(req, res, { store }) {
const boat = store.create(validateBoat(await readJson(req)))
res.setHeader('location', `/boats/${boat.code}`)
sendJson(res, 201, boat)
}
async function updateBoat(req, res, { store, params }) {
const changes = validateBoat(await readJson(req), { partial: true })
const boat = store.update(params.code, changes)
if (!boat) throw boatNotFound(params.code)
sendJson(res, 200, boat)
}
function deleteBoat(req, res, { store, params }) {
if (!store.remove(params.code)) throw boatNotFound(params.code)
res.writeHead(204)
res.end()
}
async function createQuote(req, res) {
const input = await readJson(req)
sendJson(res, 200, priceQuote(validateQuote(input)))
}
const routes = [
{ path: '/health', methods: { GET: (req, res) => sendJson(res, 200, { status: 'ok' }) } },
{ path: '/quotes', methods: { POST: createQuote } },
{ path: '/boats', methods: { GET: listBoats, POST: createBoat } },
{ path: '/boats/:code', methods: { GET: getBoat, PATCH: updateBoat, DELETE: deleteBoat } }