pnpm i mysql2
pnpm i -d @types/node
pnpm i -d typesql-cli
docker run -d --name classicmodels -p 3306:3306 -e MYSQL_ROOT_PASSWORD=password wsporto/classicmodels-mysql:8.0
The image contains the sample database from the mysqltutorial.
pnpm exec typesql init
{
"databaseUri": "mysql://root:password@localhost/classicmodels",
"sqlDir": "./src/sqls",
"target": "node"
}
src\sqls\select-products.sql
:
SELECT
productCode,
productName,
productDescription
FROM products
ORDER BY productCode
LIMIT :offset, :limit
src\sqls\select-products-total-count.sql
:
SELECT count(*) as total
FROM products
pnpm exec typesql compile --watch
Create the +page.server.ts
file:
import { conn } from "../lib/connection";
import { selectProducts, selectProductsTotalCount } from "../sqls";
const PAGE_SIZE = 5;
export async function load({ url }) {
const page = +(url.searchParams.get('page') || 1);
const products = await selectProducts(conn, {
offset: (page - 1) * PAGE_SIZE,
limit: PAGE_SIZE
});
const total = await selectProductsTotalCount(conn).then(res => res!.total);
return {
products,
total,
page,
pageSize: PAGE_SIZE
};
}