-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
114 lines (100 loc) · 3.51 KB
/
server.js
File metadata and controls
114 lines (100 loc) · 3.51 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
import express from 'express'
import fs from 'fs/promises'
import path from 'path'
import crypto from 'crypto'
const PORT = process.env.PORT || 8787
const ADMIN_API_KEY = process.env.ADMIN_API_KEY || ''
const CORS_ALLOW_ORIGIN = process.env.CORS_ALLOW_ORIGIN || '*'
const DATA_FILE = process.env.DATA_FILE || path.resolve('./workflows.json')
const app = express()
app.use(express.json({ limit: '1mb' }))
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', CORS_ALLOW_ORIGIN)
res.header('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE,OPTIONS')
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization')
if (req.method === 'OPTIONS') return res.sendStatus(200)
next()
})
async function readAll() {
try {
const content = await fs.readFile(DATA_FILE, 'utf-8')
return JSON.parse(content)
} catch (err) {
if (err.code === 'ENOENT') {
// File doesn't exist, create it with empty array
await writeAll([])
}
return []
}
}
async function writeAll(items) {
await fs.writeFile(DATA_FILE, JSON.stringify(items, null, 2))
}
function newId() { return `prompt-${Date.now()}-${crypto.randomBytes(3).toString('hex')}` }
function requireAdmin(req, res) {
const hdr = req.headers.authorization || ''
const token = hdr.startsWith('Bearer ') ? hdr.slice(7) : hdr
if (!ADMIN_API_KEY || token !== ADMIN_API_KEY) {
res.status(401).json({ error: 'Unauthorized' })
return false
}
return true
}
app.get('/workflows', async (_req, res) => {
const items = await readAll()
res.json(items.map(w => ({ ...w, source: 'public-api' })))
})
app.get('/workflows/:id', async (req, res) => {
const { id } = req.params
const items = await readAll()
const item = items.find(x => x.id === id)
if (!item) return res.status(404).json({ error: 'not found' })
res.json({ ...item, source: 'public-api' })
})
app.post('/workflows', async (req, res) => {
if (!requireAdmin(req, res)) return
const { name, prompts, author, tags } = req.body || {}
if (!name || !prompts) return res.status(400).json({ error: 'name and prompts required' })
const now = Date.now()
const item = { id: newId(), name, prompts, author, tags: Array.isArray(tags)?tags:[], createdAt:now, updatedAt:now }
const items = await readAll()
items.unshift(item)
await writeAll(items)
res.status(201).json(item)
})
app.put('/workflows/:id', async (req, res) => {
if (!requireAdmin(req, res)) return
const { id } = req.params
const patch = req.body || {}
const items = await readAll()
const i = items.findIndex(x => x.id === id)
if (i === -1) return res.status(404).json({ error: 'not found' })
items[i] = { ...items[i], ...patch, id, updatedAt: Date.now() }
await writeAll(items)
res.json(items[i])
})
app.delete('/workflows/:id', async (req, res) => {
if (!requireAdmin(req, res)) return
const { id } = req.params
const items = await readAll()
const next = items.filter(x => x.id !== id)
if (next.length === items.length) return res.status(404).json({ error: 'not found' })
await writeAll(next)
res.json({ ok: true })
})
const server = app.listen(PORT, () => console.log(`API running on http://0.0.0.0:${PORT}`))
// Graceful shutdown handling
process.on('SIGTERM', () => {
console.log('SIGTERM received, shutting down gracefully...')
server.close(() => {
console.log('Server closed')
process.exit(0)
})
})
process.on('SIGINT', () => {
console.log('SIGINT received, shutting down gracefully...')
server.close(() => {
console.log('Server closed')
process.exit(0)
})
})