-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.imba
80 lines (64 loc) · 2.11 KB
/
server.imba
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
import express from 'express'
import body-parser from 'express'
import dotenv from 'dotenv'
import node-fetch from 'node-fetch'
import cors from 'cors'
import './docs'
dotenv.config()
const app = express!
const raw_keys = process.env.API_KEYS
unless raw_keys
console.log "Please add API_KEYS to your .env file"
process.exit(-1)
const base = process.env.API_BASE
unless base
console.log "Please add API_BASE to your .env file"
process.exit(-1)
const keys = raw_keys.split(',')
let key-index = 0
def pick-key
key-index = key-index + 1
if key-index >= keys.length
key-index = 0
keys[key-index]
app.use(cors!)
app.use(body-parser.text({ type: 'text/html' }))
app.use(body-parser.json({ type: 'application/json' }))
app.get('/') do(req,res,next)
res.format
json: do next()
html: do
let out = <docs-page>
res.send String(out)
# catch-all route that returns our index.html
app.all(/.*/) do(req,res)
if process.env.REQUIRED_PREFIX and !req.path.includes(process.env.REQUIRED_PREFIX)
return res.status(403).send('Unsupported api path in scrimba proxy')
let url = new URL(base)
url.pathname = req.path
let options = {}
let headers =
'Content-Type': req.headers['content-type']
let body = req.headers['content-type'] == 'application/json' ? JSON.stringify(req.body) : req.body
if process.env.API_AUTH_TYPE == 'query'
let search = new URLSearchParams(req.query)
search.append(process.env.API_AUTH_KEY, pick-key!)
url.search = search
console.log 'fetching from', url.href
if process.env.API_AUTH_TYPE == 'bearer'
headers.authorization = "Bearer {pick-key!}";
if process.env.OPEN_AI_ORG # Should handle any extra header at some point.
headers['OpenAI-Organization'] = process.env.OPEN_AI_ORG
# TODO: Add caching of requests
let payload = await node-fetch(url,
method: req.method
body: ['POST', 'PUT'].includes(req.method) ? body : undefined
headers: headers
options: options)
try
let data = await payload.json!
res.json(data)
catch e
res.status(404).send('Not found')
console.log "Starting api wrapper for {base} with {keys.length} api keys"
imba.serve app.listen(process.env.PORT or 3000)