Skip to content

Commit

Permalink
feat: inline SQL scripts for bundlers (#345)
Browse files Browse the repository at this point in the history
  • Loading branch information
benjie authored Oct 3, 2023
2 parents 4be366a + 7a2d0a1 commit 53e0739
Show file tree
Hide file tree
Showing 5 changed files with 1,899 additions and 10 deletions.
1 change: 1 addition & 0 deletions .eslintignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
node_modules
dist
src/generated
5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@
"description": "Job queue for PostgreSQL",
"main": "dist/index.js",
"scripts": {
"prepack": "rm -Rf dist && tsc && chmod +x dist/cli.js",
"watch": "mkdir -p dist && touch dist/cli.js && chmod +x dist/cli.js && tsc --watch",
"build:sql": "node scripts/buildSqlModule.js",
"prepack": "rm -Rf dist && npm run build:sql && tsc && chmod +x dist/cli.js",
"watch": "mkdir -p dist && touch dist/cli.js && chmod +x dist/cli.js && npm run build:sql && tsc --watch",
"lint": "yarn prettier:check && eslint --ext .js,.jsx,.ts,.tsx,.graphql .",
"lint:fix": "eslint --ext .js,.jsx,.ts,.tsx,.graphql . --fix; prettier --ignore-path .eslintignore --write '**/*.{js,jsx,ts,tsx,graphql,md,json}'",
"prettier:check": "prettier --ignore-path .eslintignore --check '**/*.{js,jsx,ts,tsx,graphql,md,json}'",
Expand Down
35 changes: 35 additions & 0 deletions scripts/buildSqlModule.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
const path = require("path");
const fs = require("fs");

const sqlDir = path.join(__dirname, "../sql");
const sqlFiles = fs
.readdirSync(sqlDir)
.filter((file) => /^[0-9]{6}\.sql$/.test(file))
.sort();

/**
* Turns `str` into a String.raw expression, safely escaping backticks and
* placeholder strings.
*/
function escape(str) {
return (
"String.raw`\\\n" +
str
.replace(/`/g, '` + "`" + String.raw`')
.replace(/\$\{/g, "$$` + String.raw`{") +
"`"
);
}

const sqlModule =
"/* This file is auto-generated by `npm run build:sql`; DO NOT EDIT */\n" +
"// prettier-ignore\n" +
"export const migrations = {\n" +
sqlFiles
.map((file) => {
const sql = fs.readFileSync(path.join(sqlDir, file), "utf8");
return ` ${JSON.stringify(file)}: ${escape(sql)},`;
})
.join("\n") + "\n};\n";

fs.writeFileSync(path.join(__dirname, "../src/generated/sql.ts"), sqlModule);
Loading

0 comments on commit 53e0739

Please sign in to comment.