-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathdbConnection.js
More file actions
190 lines (170 loc) · 6.5 KB
/
dbConnection.js
File metadata and controls
190 lines (170 loc) · 6.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
/**
* Simple in-memory supabase-like mock for tests.
* Persists inserted rows and supports common chainable methods:
* select, order, range, limit, ilike, gte, lte, in, eq, maybeSingle, single,
* insert(...).select().maybeSingle(), update(...).eq(...).select().maybeSingle(),
* delete(...).eq(...)
*/
const tables = {
health_news: [],
authors: [],
categories: [],
tags: [],
news_tags: []
};
let nextId = 1000000;
function normalize(val) {
if (val === undefined || val === null) return null;
return String(val);
}
function matchFilters(row, filters) {
if (!filters || filters.length === 0) return true;
for (const f of filters) {
const col = f.col;
const v = row[col];
if (f.type === 'eq') {
if (normalize(v) !== normalize(f.val)) return false;
} else if (f.type === 'in') {
if (!Array.isArray(f.vals)) return false;
if (!f.vals.map(String).includes(String(v))) return false;
} else if (f.type === 'ilike') {
if (!v || !String(v).toLowerCase().includes(String(f.val).toLowerCase().replace(/%/g, ''))) return false;
} else if (f.type === 'gte') {
if (!(String(v) >= String(f.val))) return false;
} else if (f.type === 'lte') {
if (!(String(v) <= String(f.val))) return false;
}
}
return true;
}
function createBuilder(table, selectStmt, opts) {
const state = {
table,
select: selectStmt || '*',
opts: opts || {},
filters: [],
orderBy: null,
limitVal: null,
rangeVal: null
};
const builder = {
select(selectStmt, options) {
state.select = selectStmt || state.select;
if (options) state.opts = options;
return builder;
},
order(col, opts) { state.orderBy = { col, opts }; return builder; },
limit(n) { state.limitVal = n; return builder; },
range(a, b) { state.rangeVal = [a, b]; return builder; },
ilike(col, val) { state.filters.push({ type: 'ilike', col, val }); return builder; },
gte(col, val) { state.filters.push({ type: 'gte', col, val }); return builder; },
lte(col, val) { state.filters.push({ type: 'lte', col, val }); return builder; },
in(col, vals) { state.filters.push({ type: 'in', col, vals }); return builder; },
eq(col, val) { state.filters.push({ type: 'eq', col, val }); state.lastEq = { col, val }; return builder; },
maybeSingle: async () => {
const arr = tables[state.table] || [];
const results = arr.filter(r => matchFilters(r, state.filters));
const single = results.length > 0 ? results[0] : null;
return { data: single, error: null };
},
single: async () => {
const arr = tables[state.table] || [];
const results = arr.filter(r => matchFilters(r, state.filters));
const single = results.length > 0 ? results[0] : null;
return { data: single, error: null };
},
then(onFulfilled, onRejected) {
return (async () => {
const arr = tables[state.table] || [];
let results = arr.filter(r => matchFilters(r, state.filters));
// ordering (basic)
if (state.orderBy && state.orderBy.col) {
const col = state.orderBy.col;
const asc = state.orderBy.opts && state.orderBy.opts.ascending;
results = results.sort((a, b) => {
if (a[col] === b[col]) return 0;
if (a[col] === undefined) return 1;
if (b[col] === undefined) return -1;
if (a[col] > b[col]) return asc ? 1 : -1;
return asc ? -1 : 1;
});
}
// range/limit
if (Array.isArray(state.rangeVal)) {
const [a, b] = state.rangeVal;
results = results.slice(a, b + 1);
} else if (state.limitVal) {
results = results.slice(0, state.limitVal);
}
// head+count option
if (state.opts && state.opts.head && state.opts.count === 'exact') {
return { count: results.length, error: null };
}
return { data: results, error: null };
})().then(onFulfilled, onRejected);
}
};
return builder;
}
module.exports = {
from: (table) => {
table = table || 'unknown';
tables[table] = tables[table] || [];
return {
select: (selectStmt, options) => createBuilder(table, selectStmt, options),
insert: (rows) => {
const arr = Array.isArray(rows) ? rows : [rows];
return {
select: () => ({
maybeSingle: async () => {
const inserted = arr.map(r => {
const id = r.id || nextId++;
const now = new Date().toISOString();
const item = Object.assign({ id, created_at: now, published_at: now }, r);
tables[table].push(item);
return item;
})[0];
return { data: inserted, error: null };
}
})
};
},
update: (patch) => ({
eq: (col, val) => ({
select: () => ({
maybeSingle: async () => {
const arr = tables[table] || [];
const idx = arr.findIndex(it => String(it[col]) === String(val));
if (idx === -1) return { data: null, error: null };
arr[idx] = Object.assign({}, arr[idx], patch);
return { data: arr[idx], error: null };
}
})
})
}),
delete: () => ({
eq: (col, val) => {
const arr = tables[table] || [];
const idx = arr.findIndex(it => String(it[col]) === String(val));
if (idx === -1) return Promise.resolve({ data: null, error: null });
const removed = arr.splice(idx, 1);
return Promise.resolve({ data: removed, error: null });
}
})
};
}
};
require('dotenv').config();
const { createClient } = require('@supabase/supabase-js');
// Check if environment variables are loaded
if (!process.env.SUPABASE_URL || !process.env.SUPABASE_SERVICE_ROLE_KEY) {
console.error('❌ Missing required environment variables:');
console.error(' SUPABASE_URL:', process.env.SUPABASE_URL ? '✓ Set' : '✗ Missing');
console.error(' SUPABASE_ANON_KEY:', process.env.SUPABASE_ANON_KEY ? '✓ Set' : '✗ Missing');
console.error(' SUPABASE_SERVICE_ROLE_KEY:', process.env.SUPABASE_SERVICE_ROLE_KEY ? '✓ Set' : '✗ Missing');
console.error('\n💡 Please check your .env file contains:');
console.error(' SUPABASE_URL=your_supabase_project_url');
console.error(' SUPABASE_ANON_KEY=your_supabase_anon_key');
process.exit(1);
}
module.exports = createClient(process.env.SUPABASE_URL, process.env.SUPABASE_SERVICE_ROLE_KEY);