Skip to content

Commit 7a17e28

Browse files
committed
refactor: update imports and enhance route setup for better database management
1 parent e7eb53a commit 7a17e28

File tree

8 files changed

+83
-28
lines changed

8 files changed

+83
-28
lines changed

cloudflare-worker/eslint.config.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ export default [
99
eslint.configs.recommended,
1010
{
1111
files: ['**/*.{js,ts}'],
12+
1213
languageOptions: {
1314
ecmaVersion: 2021,
1415
sourceType: 'module',
@@ -99,6 +100,7 @@ export default [
99100
},
100101
{
101102
ignores: [
103+
'jest.config.ts',
102104
'.now/*',
103105
'*.css',
104106
'.changeset',

cloudflare-worker/src/auth0.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
/* eslint-disable no-console */
12
/**
23
* MIT License
34
*

cloudflare-worker/src/db/d1-db.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ import {
4242
PurchasesRepository,
4343
RefundsRepository,
4444
TestersRepository,
45-
} from "./db-type";
45+
} from "./db";
4646

4747
/**
4848
* Database implementation for the Cloudflare D1 database
@@ -783,7 +783,7 @@ export class CloudflareD1DB implements FeedbackFlowDB {
783783
*
784784
* @throws {Error} Always throws an error as this operation is not supported in Cloudflare D1
785785
*/
786-
async reset(newData: any): Promise<void> {
786+
async reset(_newData: any): Promise<void> {
787787
throw new Error(
788788
"Not implemented for Cloudflare D1. Use database migrations instead.",
789789
);
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
/* eslint-disable no-console */
12
/**
23
* MIT License
34
*
@@ -22,6 +23,7 @@
2223
* SOFTWARE.
2324
*/
2425

26+
import { mockData } from "../test/mock-data";
2527
import {
2628
Feedback,
2729
IdMapping,
@@ -31,6 +33,9 @@ import {
3133
Tester,
3234
} from "../types/data";
3335

36+
import { CloudflareD1DB } from "./d1-db";
37+
import { InMemoryDB } from "./in-memory-db";
38+
3439
/**
3540
* Interface for database structure
3641
*/
@@ -225,3 +230,26 @@ export abstract class FeedbackFlowDB {
225230
*/
226231
abstract restoreFromJson?(backup: string): Promise<void>;
227232
}
233+
234+
/**
235+
* Singleton instance of the database
236+
*/
237+
let dbInstance: FeedbackFlowDB | null = null;
238+
239+
/**
240+
* Get the database instance based on the environment configuration
241+
* @param env Environment configuration
242+
*/
243+
export function getDatabase(env: Env): FeedbackFlowDB {
244+
if (dbInstance === null) {
245+
// Initialiser la base de données en fonction de ENV.DB_BACKEND
246+
dbInstance =
247+
env.DB_BACKEND !== "memory"
248+
? new CloudflareD1DB(env.FeedbackFlowDB)
249+
: new InMemoryDB(mockData);
250+
251+
console.log(`Database initialized with backend: ${env.DB_BACKEND}`);
252+
}
253+
254+
return dbInstance;
255+
}

cloudflare-worker/src/db/in-memory-db.ts

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ import { v4 as uuidv4 } from "uuid";
2828

2929
import { Feedback, Publication, Purchase, Refund, Tester } from "../types/data";
3030

31-
import { DATABASESCHEMA, FeedbackFlowDB } from "./db-type";
31+
import { DATABASESCHEMA, FeedbackFlowDB } from "./db";
3232

3333
/**
3434
* In-memory database class for testing purposes
@@ -308,7 +308,8 @@ export class InMemoryDB implements FeedbackFlowDB {
308308
* @param {function} fn - Predicate function to filter purchases
309309
* @returns {Purchase|undefined} The first matching purchase or undefined if not found
310310
*/
311-
find: async (fn: (purchase: Purchase) => boolean) => this.data.purchases.find(fn),
311+
find: async (fn: (purchase: Purchase) => boolean) =>
312+
this.data.purchases.find(fn),
312313

313314
/**
314315
* Filter purchases based on the provided condition
@@ -373,7 +374,8 @@ export class InMemoryDB implements FeedbackFlowDB {
373374
* @param {function} fn - Predicate function to filter feedback
374375
* @returns {Feedback|undefined} The first matching feedback or undefined if not found
375376
*/
376-
find: async (fn: (feedback: Feedback) => boolean) => this.data.feedbacks.find(fn),
377+
find: async (fn: (feedback: Feedback) => boolean) =>
378+
this.data.feedbacks.find(fn),
377379

378380
/**
379381
* Filter feedback based on the provided condition
@@ -457,7 +459,8 @@ export class InMemoryDB implements FeedbackFlowDB {
457459
* @param {function} fn - Predicate function to filter refunds
458460
* @returns {Refund[]} Array of refunds matching the condition
459461
*/
460-
filter: async (fn: (refund: Refund) => boolean) => this.data.refunds.filter(fn),
462+
filter: async (fn: (refund: Refund) => boolean) =>
463+
this.data.refunds.filter(fn),
461464

462465
/**
463466
* Add a new refund to the database and mark the associated purchase as refunded

cloudflare-worker/src/routes/index.ts

Lines changed: 36 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -35,20 +35,18 @@ import {
3535
TesterSortCriteria,
3636
PurchaseSortCriteria,
3737
} from "../types/data";
38-
import { mockData } from "../test/mock-data";
3938
import { InMemoryDB } from "../db/in-memory-db";
39+
import { getDatabase } from "../db/db";
4040

4141
import { Router } from "./router";
4242

43-
// Use the inMemory database with mock data
44-
const db = new InMemoryDB(mockData);
45-
4643
// Tester Management
4744
const testerRoutes = (router: Router, env: Env) => {
4845
// Get all testers with pagination and sort, requires admin permission
4946
router.get(
5047
"/api/testers",
5148
async (request) => {
49+
const db = getDatabase(env);
5250
const url = new URL(request.url);
5351
const page = parseInt(url.searchParams.get("page") || "1");
5452
const limit = parseInt(url.searchParams.get("limit") || "10");
@@ -101,6 +99,8 @@ const testerRoutes = (router: Router, env: Env) => {
10199
router.post(
102100
"/api/tester",
103101
async (request) => {
102+
const db = getDatabase(env);
103+
104104
try {
105105
const { name, ids: _ids } =
106106
(await request.json()) as TesterCreateRequest;
@@ -198,6 +198,8 @@ const testerRoutes = (router: Router, env: Env) => {
198198
router.post(
199199
"/api/tester/ids",
200200
async (request) => {
201+
const db = getDatabase(env);
202+
201203
try {
202204
const testerId = router.jwtPayload.sub;
203205

@@ -311,6 +313,8 @@ const testerRoutes = (router: Router, env: Env) => {
311313
router.get(
312314
"/api/tester",
313315
async () => {
316+
const db = getDatabase(env);
317+
314318
// Get user ID from authenticated user
315319
const userId = router.jwtPayload.sub;
316320

@@ -370,6 +374,8 @@ const purchaseRoutes = (router: Router, env: Env) => {
370374
router.post(
371375
"/api/purchase",
372376
async (request) => {
377+
const db = getDatabase(env);
378+
373379
try {
374380
const data = (await request.json()) as PurchaseCreateRequest;
375381
const { date, order, description, amount, screenshot } = data;
@@ -444,6 +450,8 @@ const purchaseRoutes = (router: Router, env: Env) => {
444450
router.get(
445451
"/api/purchase/:id",
446452
async (request) => {
453+
const db = getDatabase(env);
454+
447455
const { id } = request.params;
448456

449457
// Find purchase in the database
@@ -490,6 +498,7 @@ const purchaseRoutes = (router: Router, env: Env) => {
490498
router.get(
491499
"/api/purchases/not-refunded",
492500
async (request) => {
501+
const db = getDatabase(env);
493502
const url = new URL(request.url);
494503
const page = parseInt(url.searchParams.get("page") || "1");
495504
const limit = parseInt(url.searchParams.get("limit") || "10");
@@ -579,6 +588,7 @@ const purchaseRoutes = (router: Router, env: Env) => {
579588
router.get(
580589
"/api/purchases/refunded",
581590
async (request) => {
591+
const db = getDatabase(env);
582592
const url = new URL(request.url);
583593
const page = parseInt(url.searchParams.get("page") || "1");
584594
const limit = parseInt(url.searchParams.get("limit") || "10");
@@ -671,6 +681,8 @@ const feedbackRoutes = (router: Router, env: Env) => {
671681
router.post(
672682
"/api/feedback",
673683
async (request) => {
684+
const db = getDatabase(env);
685+
674686
try {
675687
const { date, purchase, feedback } =
676688
(await request.json()) as FeedbackCreateRequest;
@@ -727,6 +739,8 @@ const feedbackRoutes = (router: Router, env: Env) => {
727739
router.post(
728740
"/api/publish",
729741
async (request) => {
742+
const db = getDatabase(env);
743+
730744
try {
731745
const { date, purchase, screenshot } =
732746
(await request.json()) as PublishCreateRequest;
@@ -782,6 +796,7 @@ const feedbackRoutes = (router: Router, env: Env) => {
782796
router.get(
783797
"/api/publish/:id",
784798
async (request) => {
799+
const db = getDatabase(env);
785800
const { id } = request.params;
786801

787802
// Find publication in the database
@@ -828,6 +843,8 @@ const refundRoutes = (router: Router, env: Env) => {
828843
router.post(
829844
"/api/refund",
830845
async (request) => {
846+
const db = getDatabase(env);
847+
831848
try {
832849
const { date, purchase, refunddate, amount } =
833850
(await request.json()) as RefundCreateRequest;
@@ -891,6 +908,7 @@ const refundRoutes = (router: Router, env: Env) => {
891908
router.get(
892909
"/api/refund/:id",
893910
async (request) => {
911+
const db = getDatabase(env);
894912
const { id } = request.params;
895913

896914
// Find refund in the database
@@ -930,6 +948,20 @@ const refundRoutes = (router: Router, env: Env) => {
930948
},
931949
env.READ_PERMISSION,
932950
);
951+
};
952+
953+
/**
954+
* Setup routes
955+
* @param router The router
956+
* @param env The environment variables
957+
*/
958+
export const setupRoutes = (router: Router, env: Env) => {
959+
const db = getDatabase(env);
960+
961+
testerRoutes(router, env);
962+
purchaseRoutes(router, env);
963+
feedbackRoutes(router, env);
964+
refundRoutes(router, env);
933965

934966
// Only allow backup route for in-memory database
935967
if (db instanceof InMemoryDB) {
@@ -963,15 +995,3 @@ const refundRoutes = (router: Router, env: Env) => {
963995
});
964996
}
965997
};
966-
967-
/**
968-
* Setup routes
969-
* @param router The router
970-
* @param env The environment variables
971-
*/
972-
export const setupRoutes = (router: Router, env: Env) => {
973-
testerRoutes(router, env);
974-
purchaseRoutes(router, env);
975-
feedbackRoutes(router, env);
976-
refundRoutes(router, env);
977-
};

cloudflare-worker/src/test/mock-data.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
2222
* SOFTWARE.
2323
*/
24-
import { DATABASESCHEMA } from "../db/db-type";
24+
import { DATABASESCHEMA } from "../db/db";
2525
import {
2626
Feedback,
2727
IdMapping,

cloudflare-worker/worker-configuration.d.ts

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
// Generated by Wrangler by running `wrangler types` (hash: 5adb303b69023bce94383df6d0cfccef)
2-
// Runtime types generated with workerd@1.20250320.0 2025-03-19
1+
// Generated by Wrangler by running `wrangler types` (hash: e9d63e061b37eb883724673694175c51)
2+
// Runtime types generated with workerd@1.20250320.0 2025-03-19
33
declare namespace Cloudflare {
44
interface Env {
55
AUTH0_CLIENT_ID: string;
@@ -15,7 +15,8 @@ declare namespace Cloudflare {
1515
ADMIN_PERMISSION: string;
1616
CRYPTOKEN: string;
1717
AUTH0_TOKEN: string;
18-
FeedbackFlowD1DB: D1Database;
18+
DB_BACKEND: string;
19+
FeedbackFlowDB: D1Database;
1920
RATE_LIMITER: RateLimit;
2021
}
2122
}
@@ -3874,7 +3875,7 @@ type AIGatewayHeaders = {
38743875
[key: string]: string | number | boolean | object;
38753876
};
38763877
type AIGatewayUniversalRequest = {
3877-
provider: AIGatewayProviders | string; // eslint-disable-line
3878+
provider: AIGatewayProviders | string;
38783879
endpoint: string;
38793880
headers: Partial<AIGatewayHeaders>;
38803881
query: unknown;
@@ -3887,7 +3888,7 @@ declare abstract class AiGateway {
38873888
patchLog(logId: string, data: AiGatewayPatchLog): Promise<void>;
38883889
getLog(logId: string): Promise<AiGatewayLog>;
38893890
run(data: AIGatewayUniversalRequest | AIGatewayUniversalRequest[]): Promise<Response>;
3890-
getUrl(provider?: AIGatewayProviders | string): Promise<string>; // eslint-disable-line
3891+
getUrl(provider?: AIGatewayProviders | string): Promise<string>;
38913892
}
38923893
interface AutoRAGInternalError extends Error {
38933894
}

0 commit comments

Comments
 (0)