Skip to content

Commit 60ad570

Browse files
committed
fix(db): refactor database handling and update version to 0.1.3
1 parent a7ab37c commit 60ad570

File tree

4 files changed

+169
-45
lines changed

4 files changed

+169
-45
lines changed

.github/workflows/publish.yml

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
name: Publish to NPM
2+
3+
on:
4+
push:
5+
tags:
6+
- 'v*'
7+
release:
8+
types: [published]
9+
10+
jobs:
11+
publish:
12+
name: Publish to NPM
13+
runs-on: ubuntu-latest
14+
permissions:
15+
contents: read
16+
id-token: write
17+
18+
steps:
19+
- name: Checkout code
20+
uses: actions/checkout@v4
21+
22+
- name: Install pnpm
23+
uses: pnpm/action-setup@v2
24+
with:
25+
version: 8
26+
27+
- name: Setup Node.js
28+
uses: actions/setup-node@v4
29+
with:
30+
node-version: 20.x
31+
cache: 'pnpm'
32+
registry-url: 'https://registry.npmjs.org'
33+
34+
- name: Install dependencies
35+
run: pnpm install --frozen-lockfile
36+
37+
- name: Run linter
38+
run: pnpm lint
39+
40+
- name: Run tests
41+
run: pnpm test
42+
43+
- name: Build project
44+
run: pnpm build
45+
46+
- name: Publish to NPM
47+
run: pnpm publish --no-git-checks
48+
env:
49+
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}

bin/cli.cjs

Lines changed: 66 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -22,8 +22,14 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
2222
}) : target, mod));
2323

2424
//#endregion
25+
let path = require("path");
26+
path = __toESM(path);
2527
let better_sqlite3 = require("better-sqlite3");
2628
better_sqlite3 = __toESM(better_sqlite3);
29+
let url = require("url");
30+
url = __toESM(url);
31+
let fs = require("fs");
32+
fs = __toESM(fs);
2733
let __h3ravel_shared = require("@h3ravel/shared");
2834
__h3ravel_shared = __toESM(__h3ravel_shared);
2935
let axios = require("axios");
@@ -38,11 +44,33 @@ let __ngrok_ngrok = require("@ngrok/ngrok");
3844
__ngrok_ngrok = __toESM(__ngrok_ngrok);
3945

4046
//#region src/db.ts
41-
const db = new better_sqlite3.default("app.db");
42-
db.pragma("journal_mode = WAL");
43-
function init(table = "json_store") {
44-
return db.exec(`
45-
CREATE TABLE IF NOT EXISTS ${table} (
47+
let db;
48+
const __dirname$1 = (0, path.dirname)((0, url.fileURLToPath)(require("url").pathToFileURL(__filename).href));
49+
const dirPath = path.default.normalize(path.default.join(__dirname$1, "..", "data"));
50+
(0, fs.mkdirSync)(dirPath, { recursive: true });
51+
/**
52+
* Hook to get or set the database instance.
53+
*
54+
* @returns
55+
*/
56+
const useDb = () => {
57+
return [() => db, (newDb) => {
58+
db = newDb;
59+
const [{ journal_mode }] = db.pragma("journal_mode");
60+
if (journal_mode !== "wal") db.pragma("journal_mode = WAL");
61+
}];
62+
};
63+
const [getDatabase, setDatabase] = useDb();
64+
setDatabase(new better_sqlite3.default(path.default.join(dirPath, "app.db")));
65+
/**
66+
* Initialize the database
67+
*
68+
* @param table
69+
* @returns
70+
*/
71+
function init() {
72+
return getDatabase().exec(`
73+
CREATE TABLE IF NOT EXISTS json_store (
4674
id INTEGER PRIMARY KEY AUTOINCREMENT,
4775
key TEXT UNIQUE,
4876
value TEXT
@@ -56,30 +84,41 @@ function init(table = "json_store") {
5684
* @param value
5785
* @returns
5886
*/
59-
function write(key, value, table = "json_store") {
87+
function write(key, value) {
88+
const db$1 = getDatabase();
6089
if (typeof value === "boolean") value = value ? "1" : "0";
6190
if (value instanceof Object) value = JSON.stringify(value);
62-
return db.prepare(`INSERT INTO ${table} (key, value)
91+
return db$1.prepare(`INSERT INTO json_store (key, value)
6392
VALUES (?, ?)
6493
ON CONFLICT(key) DO UPDATE SET value=excluded.value
6594
`).run(key, value).lastInsertRowid;
6695
}
67-
function remove(key, table = "json_store") {
68-
return db.prepare(`DELETE FROM ${table} WHERE key = ?`).run(key).lastInsertRowid;
96+
/**
97+
* Remove a value from the database
98+
*
99+
* @param key
100+
* @param table
101+
* @returns
102+
*/
103+
function remove(key) {
104+
return getDatabase().prepare("DELETE FROM json_store WHERE key = ?").run(key).lastInsertRowid;
69105
}
70106
/**
71107
* Read a value from the database
72108
*
73109
* @param key
74110
* @returns
75111
*/
76-
function read(key, table = "json_store") {
77-
const row = db.prepare(`SELECT * FROM ${table} WHERE key = ?`).get(key);
78-
if (row) try {
79-
return JSON.parse(row.value);
80-
} catch {
81-
return row.value;
82-
}
112+
function read(key) {
113+
const db$1 = getDatabase();
114+
try {
115+
const row = db$1.prepare("SELECT * FROM json_store WHERE key = ?").get(key);
116+
if (row) try {
117+
return JSON.parse(row.value);
118+
} catch {
119+
return row.value;
120+
}
121+
} catch {}
83122
return null;
84123
}
85124

@@ -260,14 +299,14 @@ async function executeSchema(schema, options) {
260299
if (schema.method == "GET") params = options;
261300
if (schema.method == "POST") data = options;
262301
const pathVars = [...schema.endpoint.matchAll(/\{([^}]+)\}/g)].map((match) => match[1]);
263-
if (pathVars.length >= 0) for (const path of pathVars) schema.endpoint = schema.endpoint.replace("{" + path + "}", options[path]);
264-
const url = new URL(schema.endpoint, config.apiBaseURL || "https://api.paystack.co");
302+
if (pathVars.length >= 0) for (const path$2 of pathVars) schema.endpoint = schema.endpoint.replace("{" + path$2 + "}", options[path$2]);
303+
const url$1 = new URL(schema.endpoint, config.apiBaseURL || "https://api.paystack.co");
265304
params = {
266305
...params,
267-
...Object.fromEntries(url.searchParams.entries())
306+
...Object.fromEntries(url$1.searchParams.entries())
268307
};
269308
axios_default.request({
270-
url: url.pathname,
309+
url: url$1.pathname,
271310
method: schema.method,
272311
params,
273312
data,
@@ -2895,10 +2934,10 @@ async function refreshIntegration() {
28952934
* @param domain
28962935
* @returns
28972936
*/
2898-
function setWebhook(url, token, integrationId, domain = "test") {
2937+
function setWebhook(url$1, token, integrationId, domain = "test") {
28992938
return new Promise((resolve, reject) => {
29002939
const data = {
2901-
[domain + "_webhook_endpoint"]: url,
2940+
[domain + "_webhook_endpoint"]: url$1,
29022941
integration: integrationId
29032942
};
29042943
axios_default.put("/integration/webhooks", data, { headers: {
@@ -2908,7 +2947,7 @@ function setWebhook(url, token, integrationId, domain = "test") {
29082947
const integration = read("selected_integration");
29092948
write("selected_integration", {
29102949
...integration,
2911-
[domain + "_webhook_endpoint"]: url
2950+
[domain + "_webhook_endpoint"]: url$1
29122951
});
29132952
resolve(resp.data.message);
29142953
}).catch((err) => {
@@ -3209,16 +3248,16 @@ var WebhookCommand = class extends __h3ravel_musket.Command {
32093248
this.error("ERROR: Your session has expired. Please run the `login` command to sign in again.");
32103249
return;
32113250
}
3212-
const url = parseURL(local_route);
3213-
if (!url.port) url.port = "8000";
3214-
if (!url.search || url.search == "?") url.search = "";
3251+
const url$1 = parseURL(local_route);
3252+
if (!url$1.port) url$1.port = "8000";
3253+
if (!url$1.search || url$1.search == "?") url$1.search = "";
32153254
try {
32163255
await __ngrok_ngrok.default.kill();
32173256
} catch {
32183257
this.debug("No existing ngrok process found to kill.");
32193258
}
32203259
const ngrokURL = (await __ngrok_ngrok.default.forward({
3221-
addr: url.port,
3260+
addr: url$1.port,
32223261
authtoken: config.ngrokAuthToken || process.env.NGROK_AUTH_TOKEN,
32233262
domain: process.env.NGROK_DOMAIN
32243263
})).url();

bin/cli.js

Lines changed: 53 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
#!/usr/bin/env node
2+
import path, { dirname } from "path";
23
import Database from "better-sqlite3";
4+
import { fileURLToPath } from "url";
5+
import { mkdirSync } from "fs";
36
import { Logger } from "@h3ravel/shared";
47
import axios from "axios";
58
import { Command, Kernel } from "@h3ravel/musket";
@@ -8,11 +11,33 @@ import crypto from "crypto";
811
import ngrok from "@ngrok/ngrok";
912

1013
//#region src/db.ts
11-
const db = new Database("app.db");
12-
db.pragma("journal_mode = WAL");
13-
function init(table = "json_store") {
14-
return db.exec(`
15-
CREATE TABLE IF NOT EXISTS ${table} (
14+
let db;
15+
const __dirname = dirname(fileURLToPath(import.meta.url));
16+
const dirPath = path.normalize(path.join(__dirname, "..", "data"));
17+
mkdirSync(dirPath, { recursive: true });
18+
/**
19+
* Hook to get or set the database instance.
20+
*
21+
* @returns
22+
*/
23+
const useDb = () => {
24+
return [() => db, (newDb) => {
25+
db = newDb;
26+
const [{ journal_mode }] = db.pragma("journal_mode");
27+
if (journal_mode !== "wal") db.pragma("journal_mode = WAL");
28+
}];
29+
};
30+
const [getDatabase, setDatabase] = useDb();
31+
setDatabase(new Database(path.join(dirPath, "app.db")));
32+
/**
33+
* Initialize the database
34+
*
35+
* @param table
36+
* @returns
37+
*/
38+
function init() {
39+
return getDatabase().exec(`
40+
CREATE TABLE IF NOT EXISTS json_store (
1641
id INTEGER PRIMARY KEY AUTOINCREMENT,
1742
key TEXT UNIQUE,
1843
value TEXT
@@ -26,30 +51,41 @@ function init(table = "json_store") {
2651
* @param value
2752
* @returns
2853
*/
29-
function write(key, value, table = "json_store") {
54+
function write(key, value) {
55+
const db$1 = getDatabase();
3056
if (typeof value === "boolean") value = value ? "1" : "0";
3157
if (value instanceof Object) value = JSON.stringify(value);
32-
return db.prepare(`INSERT INTO ${table} (key, value)
58+
return db$1.prepare(`INSERT INTO json_store (key, value)
3359
VALUES (?, ?)
3460
ON CONFLICT(key) DO UPDATE SET value=excluded.value
3561
`).run(key, value).lastInsertRowid;
3662
}
37-
function remove(key, table = "json_store") {
38-
return db.prepare(`DELETE FROM ${table} WHERE key = ?`).run(key).lastInsertRowid;
63+
/**
64+
* Remove a value from the database
65+
*
66+
* @param key
67+
* @param table
68+
* @returns
69+
*/
70+
function remove(key) {
71+
return getDatabase().prepare("DELETE FROM json_store WHERE key = ?").run(key).lastInsertRowid;
3972
}
4073
/**
4174
* Read a value from the database
4275
*
4376
* @param key
4477
* @returns
4578
*/
46-
function read(key, table = "json_store") {
47-
const row = db.prepare(`SELECT * FROM ${table} WHERE key = ?`).get(key);
48-
if (row) try {
49-
return JSON.parse(row.value);
50-
} catch {
51-
return row.value;
52-
}
79+
function read(key) {
80+
const db$1 = getDatabase();
81+
try {
82+
const row = db$1.prepare("SELECT * FROM json_store WHERE key = ?").get(key);
83+
if (row) try {
84+
return JSON.parse(row.value);
85+
} catch {
86+
return row.value;
87+
}
88+
} catch {}
5389
return null;
5490
}
5591

@@ -230,7 +266,7 @@ async function executeSchema(schema, options) {
230266
if (schema.method == "GET") params = options;
231267
if (schema.method == "POST") data = options;
232268
const pathVars = [...schema.endpoint.matchAll(/\{([^}]+)\}/g)].map((match) => match[1]);
233-
if (pathVars.length >= 0) for (const path of pathVars) schema.endpoint = schema.endpoint.replace("{" + path + "}", options[path]);
269+
if (pathVars.length >= 0) for (const path$1 of pathVars) schema.endpoint = schema.endpoint.replace("{" + path$1 + "}", options[path$1]);
234270
const url = new URL(schema.endpoint, config.apiBaseURL || "https://api.paystack.co");
235271
params = {
236272
...params,

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
{
22
"name": "@toneflix/paystack-cli",
33
"type": "module",
4-
"version": "0.1.2",
4+
"version": "0.1.3",
55
"description": "Interact with the Paystack API, test webhooks locally, and manage your integration settings without leaving your command line.",
66
"main": "bin/cli.js",
77
"private": false,

0 commit comments

Comments
 (0)