src/lib/server/db.js
import knex from 'knex';
import { env } from '$env/dynamic/private';
export default knex({
client: 'mysql2',
connection: {
host: env.DB_HOST,
port: 3306,
user: env.DB_USER,
password: env.DB_PASSWORD,
database: env.DB_NAME
},
pool: {
min: 2,
max: 20
}
});
src/routes/api/district/+server.js
import db from '$lib/server/db';
/** @type {import('./$types').RequestHandler} */
export async function GET({ url }) {
const provinceCode = url.searchParams.get('provinceCode');
const districts = await db('catm').whereRaw(`code like ? and length(code)=4`, [`${provinceCode}%`])
.orderBy('name');
return new Response(JSON.stringify({ districts }));
};
run.sh
DB_HOST=localhost \
DB_USER=root \
DB_PASSWORD=xxxxxx \
DB_NAME=test \
npm run dev
Call api
curl http://localhost:5173/api/district?provinceCode=44