-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
183 lines (162 loc) · 4.91 KB
/
Copy pathserver.ts
File metadata and controls
183 lines (162 loc) · 4.91 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
import express from 'express';
import { createServer as createViteServer } from 'vite';
import { GoogleSpreadsheet } from 'google-spreadsheet';
import { JWT } from 'google-auth-library';
import dotenv from 'dotenv';
import crypto from 'crypto';
dotenv.config();
const app = express();
const PORT = 3000;
app.use(express.json());
// Initialize Google Sheets
let doc: GoogleSpreadsheet | null = null;
async function initGoogleSheets() {
const email = process.env.GOOGLE_SERVICE_ACCOUNT_EMAIL;
const key = process.env.GOOGLE_PRIVATE_KEY;
const sheetId = process.env.GOOGLE_SPREADSHEET_ID;
if (!email || !key || !sheetId) {
console.warn('Google Sheets credentials not found. App will run in mock mode.');
return;
}
try {
const formattedKey = key.replace(/\\n/g, '\n');
const serviceAccountAuth = new JWT({
email: email,
key: formattedKey,
scopes: ['https://www.googleapis.com/auth/spreadsheets'],
});
doc = new GoogleSpreadsheet(sheetId, serviceAccountAuth);
await doc.loadInfo();
console.log(`Connected to Google Sheet: ${doc.title}`);
} catch (error) {
console.error('Failed to initialize Google Sheets:', error);
doc = null;
}
}
// In-memory fallback if Google Sheets is not configured
const mockSales = [
{
id: '1',
title: 'Huge Multi-Family Garage Sale',
description: 'Furniture, clothes, electronics, and more!',
address: '123 Main St, Anytown, USA',
lat: 37.7749,
lng: -122.4194,
date: '2025-06-15',
time: '08:00 AM - 02:00 PM',
createdAt: new Date().toISOString(),
},
{
id: '2',
title: 'Moving Sale - Everything Must Go',
description: 'Tools, garden equipment, kitchenware.',
address: '456 Oak Ave, Anytown, USA',
lat: 37.7849,
lng: -122.4094,
date: '2025-06-16',
time: '09:00 AM - 04:00 PM',
createdAt: new Date().toISOString(),
}
];
// API Routes
app.get('/api/sales', async (req, res) => {
if (!doc) {
return res.json(mockSales);
}
try {
const sheet = doc.sheetsByIndex[0];
const rows = await sheet.getRows();
const sales = rows.map(row => ({
id: row.get('id'),
title: row.get('title'),
description: row.get('description'),
address: row.get('address'),
lat: parseFloat(row.get('lat')),
lng: parseFloat(row.get('lng')),
date: row.get('date'),
time: row.get('time'),
createdAt: row.get('createdAt'),
}));
res.json(sales);
} catch (error) {
console.error('Error fetching sales:', error);
res.status(500).json({ error: 'Failed to fetch sales' });
}
});
app.post('/api/sales', async (req, res) => {
const { title, description, address, lat, lng, date, time } = req.body;
const newSale = {
id: crypto.randomUUID(),
title,
description,
address,
lat,
lng,
date,
time,
createdAt: new Date().toISOString(),
};
if (!doc) {
mockSales.push(newSale);
return res.status(201).json(newSale);
}
try {
const sheet = doc.sheetsByIndex[0];
await sheet.addRow(newSale);
res.status(201).json(newSale);
} catch (error) {
console.error('Error adding sale:', error);
res.status(500).json({ error: 'Failed to add sale' });
}
});
// Geocoding proxy to Nominatim (OpenStreetMap) to avoid CORS/frontend issues
app.get('/api/geocode', async (req, res) => {
const { q } = req.query;
if (!q || typeof q !== 'string') {
return res.status(400).json({ error: 'Missing query parameter' });
}
try {
const response = await fetch(`https://nominatim.openstreetmap.org/search?format=json&addressdetails=1&limit=5&q=${encodeURIComponent(q)}`, {
headers: {
'User-Agent': 'TuunzGarageSales/1.0'
}
});
const data = (await response.json()) as any[];
const suggestions = data.map((item: any) => {
const addr = item.address;
const parts: string[] = [];
const house = [addr?.house_number, addr?.road].filter(Boolean).join(' ');
if (house) parts.push(house);
const city = addr?.city || addr?.town || addr?.village || addr?.hamlet;
if (city) parts.push(city);
if (addr?.state) parts.push(addr.state);
if (addr?.postcode) parts.push(addr.postcode);
return {
label: parts.length >= 2 ? parts.join(', ') : item.display_name,
fullLabel: item.display_name,
lat: item.lat,
lon: item.lon,
};
});
res.json(suggestions);
} catch (error) {
console.error('Geocoding error:', error);
res.status(500).json({ error: 'Geocoding failed' });
}
});
async function startServer() {
await initGoogleSheets();
if (process.env.NODE_ENV !== 'production') {
const vite = await createViteServer({
server: { middlewareMode: true },
appType: 'spa',
});
app.use(vite.middlewares);
} else {
app.use(express.static('dist'));
}
app.listen(PORT, '0.0.0.0', () => {
console.log(`Server running on http://localhost:${PORT}`);
});
}
startServer();