Skip to content

Commit f202414

Browse files
author
Daniele Briggi
committed
featpostgres): allow to use any token
1 parent 8e19ee2 commit f202414

File tree

7 files changed

+65
-87
lines changed

7 files changed

+65
-87
lines changed

examples/sport-tracker-app/package.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,10 +13,11 @@
1313
"vite": "^7.0.0"
1414
},
1515
"dependencies": {
16-
"@sqliteai/sqlite-wasm": "*",
16+
"@sqliteai/sqlite-wasm": "dev",
1717
"@types/react": "^19.1.8",
1818
"@types/react-dom": "^19.1.6",
1919
"@vitejs/plugin-react": "^4.6.0",
20+
"pg": "^8.17.2",
2021
"react": "^19.1.0",
2122
"react-dom": "^19.1.0"
2223
}
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
-- PostgreSQL schema
2+
-- Use this schema to create the remote database on PostgreSQL/PostgREST
3+
4+
CREATE TABLE IF NOT EXISTS users_sport (
5+
id TEXT PRIMARY KEY NOT NULL, -- UUID's HIGHLY RECOMMENDED for global uniqueness
6+
name TEXT UNIQUE NOT NULL DEFAULT ''
7+
);
8+
9+
CREATE TABLE IF NOT EXISTS activities (
10+
id TEXT PRIMARY KEY NOT NULL, -- UUID's HIGHLY RECOMMENDED for global uniqueness
11+
type TEXT NOT NULL DEFAULT 'runnning',
12+
duration INTEGER,
13+
distance DOUBLE PRECISION,
14+
calories INTEGER,
15+
date TEXT,
16+
notes TEXT,
17+
user_id TEXT REFERENCES users_sport (id)
18+
);
19+
20+
CREATE TABLE IF NOT EXISTS workouts (
21+
id TEXT PRIMARY KEY NOT NULL, -- UUID's HIGHLY RECOMMENDED for global uniqueness
22+
name TEXT,
23+
type TEXT,
24+
duration INTEGER,
25+
exercises TEXT,
26+
date TEXT,
27+
completed INTEGER DEFAULT 0,
28+
user_id TEXT
29+
);

examples/sport-tracker-app/sport-tracker-schema.sql

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
-- SQL schema
22
-- Use this exact schema to create the remote database on the on SQLite Cloud
33

4-
CREATE TABLE IF NOT EXISTS users (
4+
CREATE TABLE IF NOT EXISTS users_sport (
55
id TEXT PRIMARY KEY NOT NULL, -- UUID's HIGHLY RECOMMENDED for global uniqueness
66
name TEXT UNIQUE NOT NULL DEFAULT ''
77
);
@@ -15,7 +15,7 @@ CREATE TABLE IF NOT EXISTS activities (
1515
date TEXT,
1616
notes TEXT,
1717
user_id TEXT,
18-
FOREIGN KEY (user_id) REFERENCES users (id)
18+
FOREIGN KEY (user_id) REFERENCES users_sport (id)
1919
);
2020

2121
CREATE TABLE IF NOT EXISTS workouts (

examples/sport-tracker-app/src/SQLiteSync.ts

Lines changed: 17 additions & 66 deletions
Original file line numberDiff line numberDiff line change
@@ -111,21 +111,23 @@ export class SQLiteSync {
111111

112112
const now = new Date();
113113
if (!token) {
114-
console.log("SQLite Sync: No token available, requesting new one from API");
115-
const tokenData = await this.fetchNewToken(userId, name);
116-
localStorage.setItem(
117-
SQLiteSync.TOKEN_KEY_PREFIX,
118-
JSON.stringify(tokenData)
114+
console.log(
115+
"SQLite Sync: No token available, requesting new one from API",
119116
);
117+
const tokenData = await this.fetchNewToken(userId, name);
118+
// localStorage.setItem(
119+
// SQLiteSync.TOKEN_KEY_PREFIX,
120+
// JSON.stringify(tokenData),
121+
// );
120122
token = tokenData.token;
121123
console.log("SQLite Sync: New token obtained and stored in localStorage");
122124
} else if (tokenExpiry && tokenExpiry <= now) {
123125
console.warn("SQLite Sync: Token expired, requesting new one from API");
124126
const tokenData = await this.fetchNewToken(userId, name);
125-
localStorage.setItem(
126-
SQLiteSync.TOKEN_KEY_PREFIX,
127-
JSON.stringify(tokenData)
128-
);
127+
// localStorage.setItem(
128+
// SQLiteSync.TOKEN_KEY_PREFIX,
129+
// JSON.stringify(tokenData),
130+
// );
129131
token = tokenData.token;
130132
console.log("SQLite Sync: New token obtained and stored in localStorage");
131133
} else {
@@ -143,69 +145,18 @@ export class SQLiteSync {
143145
*/
144146
private async fetchNewToken(
145147
userId: string,
146-
name: string
148+
name: string,
147149
): Promise<Record<string, any>> {
148-
const response = await fetch(
149-
`${import.meta.env.VITE_SQLITECLOUD_API_URL}/v2/tokens`,
150-
{
151-
method: "POST",
152-
headers: {
153-
"Content-Type": "application/json",
154-
Authorization: `Bearer ${import.meta.env.VITE_SQLITECLOUD_API_KEY}`,
155-
},
156-
body: JSON.stringify({
157-
userId,
158-
name,
159-
expiresAt: new Date(
160-
Date.now() + SQLiteSync.TOKEN_EXPIRY_MINUTES * 60 * 1000
161-
).toISOString(),
162-
}),
163-
}
164-
);
165-
166-
if (!response.ok) {
167-
throw new Error(`Failed to get token: ${response.status}`);
168-
}
169-
170-
const result = await response.json();
171-
return result.data;
150+
const jwt = await Promise.resolve(import.meta.env.VITE_SQLITECLOUD_API_KEY);
151+
return {
152+
token: jwt
153+
};
172154
}
173155

174156
/**
175157
* Checks if a valid token exists in localStorage
176158
*/
177159
static hasValidToken(): boolean {
178-
const storedTokenData = localStorage.getItem(SQLiteSync.TOKEN_KEY_PREFIX);
179-
180-
if (!storedTokenData) {
181-
console.log("SQLite Sync: No token data found in localStorage");
182-
return false;
183-
}
184-
185-
try {
186-
const parsed: TokenData = JSON.parse(storedTokenData);
187-
188-
// Check if token exists
189-
if (!parsed.token) {
190-
console.log("SQLite Sync: Token data exists but no token found");
191-
return false;
192-
}
193-
194-
// Check if token is expired
195-
if (parsed.expiresAt) {
196-
const tokenExpiry = new Date(parsed.expiresAt);
197-
const now = new Date();
198-
if (tokenExpiry <= now) {
199-
console.log("SQLite Sync: Token found but expired");
200-
return false;
201-
}
202-
}
203-
204-
console.log("SQLite Sync: Valid token found in localStorage");
205-
return true;
206-
} catch (e) {
207-
console.error("SQLite Sync: Failed to parse stored token:", e);
208-
return false;
209-
}
160+
return false;
210161
}
211162
}

examples/sport-tracker-app/src/components/UserCreation.tsx

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -15,26 +15,22 @@ interface UserCreationProps {
1515
*/
1616
const fetchRemoteUsers = async (): Promise<User[]> => {
1717
const response = await fetch(
18-
`${import.meta.env.VITE_SQLITECLOUD_API_URL}/v2/weblite/sql`,
18+
`${import.meta.env.VITE_SQLITECLOUD_API_URL}/rest/v1/users_sport?select=id,name`,
1919
{
20-
method: "POST",
20+
method: "GET",
2121
headers: {
22-
"Content-Type": "application/json",
23-
Authorization: `Bearer ${import.meta.env.VITE_SQLITECLOUD_API_KEY}`,
22+
Accept: "application/json",
23+
Authorization: `Bearer ${import.meta.env.VITE_SQLITECLOUD_API_KEY || ""}`,
2424
},
25-
body: JSON.stringify({
26-
sql: "SELECT id, name FROM users;",
27-
database: import.meta.env.VITE_SQLITECLOUD_DATABASE || "",
28-
}),
2925
}
3026
);
31-
27+
3228
if (!response.ok) {
3329
throw new Error(`Failed to fetch users: ${response.status}`);
3430
}
3531

3632
const result = await response.json();
37-
return result.data;
33+
return result as User[];
3834
};
3935

4036
const UserCreation: React.FC<UserCreationProps> = ({
@@ -58,6 +54,7 @@ const UserCreation: React.FC<UserCreationProps> = ({
5854
setRemoteUsers(users);
5955
} catch (error) {
6056
console.error("Failed to load remote users:", error);
57+
alert("Failed to load remote users. Error: " + error);
6158
} finally {
6259
setIsLoadingRemoteUsers(false);
6360
}

examples/sport-tracker-app/src/db/databaseOperations.ts

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -216,7 +216,7 @@ export const getDatabaseOperations = (db: any) => ({
216216

217217
try {
218218
db.exec({
219-
sql: "INSERT INTO users (id, name) VALUES (?, ?)",
219+
sql: "INSERT INTO users_sport (id, name) VALUES (?, ?)",
220220
bind: [userId, name],
221221
});
222222
return { id: userId, name };
@@ -228,7 +228,7 @@ export const getDatabaseOperations = (db: any) => ({
228228
getUsers() {
229229
const users: any[] = [];
230230
db.exec({
231-
sql: "SELECT id, name FROM users ORDER BY name",
231+
sql: "SELECT id, name FROM users_sport ORDER BY name",
232232
callback: (row: any) => {
233233
users.push({
234234
id: row[0],
@@ -243,7 +243,7 @@ export const getDatabaseOperations = (db: any) => ({
243243
const { id } = data;
244244
let user = null;
245245
db.exec({
246-
sql: "SELECT id, name FROM users WHERE id = ?",
246+
sql: "SELECT id, name FROM users_sport WHERE id = ?",
247247
bind: [id],
248248
callback: (row: any) => {
249249
user = {
@@ -268,7 +268,7 @@ export const getDatabaseOperations = (db: any) => ({
268268

269269
// Get total counts (always show total for comparison)
270270
db.exec({
271-
sql: "SELECT COUNT(*) FROM users WHERE name != ?",
271+
sql: "SELECT COUNT(*) FROM users_sport WHERE name != ?",
272272
bind: ["coach"],
273273
callback: (row: any) => (counts.totalUsers = row[0]),
274274
});
@@ -287,7 +287,7 @@ export const getDatabaseOperations = (db: any) => ({
287287
if (user_id && !is_coach) {
288288
// Regular user - count only their data
289289
db.exec({
290-
sql: "SELECT COUNT(*) FROM users WHERE name != ?",
290+
sql: "SELECT COUNT(*) FROM users_sport WHERE name != ?",
291291
bind: ["coach"],
292292
callback: (row: any) => (counts.users = row[0]),
293293
});

examples/sport-tracker-app/src/db/sqliteSyncOperations.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ export const getSqliteSyncOperations = (db: any) => ({
2626
* This will push changes to the cloud and check for changes from the cloud.
2727
* The first attempt may not find anything to apply, but subsequent attempts
2828
* will find changes if they exist.
29-
*/
29+
*/
3030
sqliteSyncNetworkSync() {
3131
console.log("SQLite Sync - Starting sync...");
3232
db.exec("SELECT cloudsync_network_sync(1000, 2);");
@@ -38,7 +38,7 @@ export const getSqliteSyncOperations = (db: any) => ({
3838
*/
3939
sqliteSyncSendChanges() {
4040
console.log(
41-
"SQLite Sync - Sending changes to your the SQLite Cloud node..."
41+
"SQLite Sync - Sending changes to your the SQLite Cloud node...",
4242
);
4343
db.exec("SELECT cloudsync_network_send_changes();");
4444
console.log("SQLite Sync - Changes sent");
@@ -84,7 +84,7 @@ export const initSQLiteSync = (db: any) => {
8484
}
8585

8686
// Initialize SQLite Sync
87-
db.exec(`SELECT cloudsync_init('users');`);
87+
db.exec(`SELECT cloudsync_init('users_sport');`);
8888
db.exec(`SELECT cloudsync_init('activities');`);
8989
db.exec(`SELECT cloudsync_init('workouts');`);
9090
// ...or initialize all tables at once

0 commit comments

Comments
 (0)