Skip to content

Instantly share code, notes, and snippets.

@siteslave
Last active November 6, 2023 07:06
Show Gist options
  • Save siteslave/5d6a985bc3526ca603b51dd8c6588b9b to your computer and use it in GitHub Desktop.
Save siteslave/5d6a985bc3526ca603b51dd8c6588b9b to your computer and use it in GitHub Desktop.
Sveltekit API

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment