-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
181 lines (158 loc) · 5.89 KB
/
Copy pathserver.js
File metadata and controls
181 lines (158 loc) · 5.89 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
import 'dotenv/config';
import express from 'express';
import cors from 'cors';
import { createClient } from '@supabase/supabase-js';
import path from 'path';
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const app = express();
const PORT = process.env.PORT || 3000;
const supabaseUrl = process.env.SUPABASE_URL || '';
const supabaseKey = process.env.SUPABASE_ANON_KEY || '';
const supabaseConfigured = supabaseUrl && supabaseKey && supabaseUrl !== 'YOUR_SUPABASE_URL' && supabaseKey !== 'YOUR_SUPABASE_ANON_KEY';
const supabase = supabaseConfigured ? createClient(supabaseUrl, supabaseKey) : null;
app.use(cors());
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true, limit: '10mb' }));
app.use(express.static(path.join(__dirname, 'public')));
app.use('/admin.html', express.static(path.join(__dirname, 'admin.html')));
const verifyPassword = (req, res, next) => {
const auth = req.headers.authorization;
if (auth === 'Bearer tjx20070827') {
next();
} else {
res.status(401).json({ error: 'Unauthorized' });
}
};
function requireSupabase(res) {
if (!supabase) {
res.status(503).json({
error: 'Supabase 未配置。请在 .env 文件中设置 SUPABASE_URL 和 SUPABASE_ANON_KEY,或部署到 Vercel 时在环境变量中配置。'
});
return false;
}
return true;
}
app.get('/api/posts', async (req, res) => {
if (!requireSupabase(res)) return;
try {
const { data: posts, error: postsError } = await supabase
.from('posts')
.select('*')
.order('created_at', { ascending: false });
if (postsError) throw postsError;
const { data: files, error: filesError } = await supabase
.from('post_files')
.select('*');
if (filesError) throw filesError;
const filesByPostId = {};
for (const f of files) {
if (!filesByPostId[f.post_id]) filesByPostId[f.post_id] = [];
filesByPostId[f.post_id].push(f);
}
res.json(posts.map(post => ({
...post,
files: filesByPostId[post.id] || []
})));
} catch (err) {
res.status(500).json({ error: err.message });
}
});
app.post('/api/posts', verifyPassword, async (req, res) => {
if (!requireSupabase(res)) return;
try {
const { title, content, code, code_type } = req.body;
const { data, error } = await supabase
.from('posts')
.insert([{
title,
content,
code,
code_type: code_type || 'python',
created_at: new Date().toISOString()
}])
.select();
if (error) throw error;
res.json(data[0]);
} catch (err) {
res.status(500).json({ error: err.message });
}
});
app.post('/api/upload', verifyPassword, async (req, res) => {
if (!requireSupabase(res)) return;
try {
const { file_name, file_type, content, mime } = req.body;
if (!content || !file_name) return res.status(400).json({ error: 'Missing file data' });
const fileExt = file_name.split('.').pop();
const fileName = `${Date.now()}.${fileExt}`;
const buffer = Buffer.from(content, 'base64');
const { data, error } = await supabase.storage
.from('uploads')
.upload(fileName, buffer, {
contentType: mime || 'application/octet-stream',
upsert: false
});
if (error) {
if (error.message?.includes('bucket') || error.message?.includes('not found') || error.statusCode === '404') {
throw new Error('Storage "uploads" 存储桶不存在!请去 Supabase Dashboard → Storage → New Bucket 创建名为 uploads 的公开存储桶');
}
throw new Error('上传失败: ' + error.message);
}
const { data: { publicUrl } } = supabase.storage
.from('uploads')
.getPublicUrl(fileName);
res.json({ url: publicUrl, name: file_name });
} catch (err) {
console.error('[Upload Error]', err);
res.status(500).json({ error: err.message });
}
});
app.post('/api/posts/:id/files', verifyPassword, async (req, res) => {
if (!requireSupabase(res)) return;
try {
const { files } = req.body;
const postId = req.params.id;
for (const file of files) {
const { error } = await supabase
.from('post_files')
.insert([{
post_id: postId,
url: file.url,
name: file.name,
type: file.type
}]);
if (error) throw error;
}
res.json({ success: true });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
app.delete('/api/posts/:id', verifyPassword, async (req, res) => {
if (!requireSupabase(res)) return;
try {
const { error: filesError } = await supabase
.from('post_files')
.delete()
.eq('post_id', req.params.id);
if (filesError) throw filesError;
const { error } = await supabase
.from('posts')
.delete()
.eq('id', req.params.id);
if (error) throw error;
res.json({ success: true });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
if (!supabaseConfigured) {
console.log('\n⚠️ Supabase 未配置!API 将返回 503 错误。');
console.log('请创建 .env 文件并填入:');
console.log(' SUPABASE_URL=https://你的项目.supabase.co');
console.log(' SUPABASE_ANON_KEY=你的anon_key\n');
}
});