aripbae commited on
Commit
4896609
·
verified ·
1 Parent(s): bc93ab9

Update index.js

Browse files
Files changed (1) hide show
  1. index.js +50 -34
index.js CHANGED
@@ -43,45 +43,61 @@ const isBase64 = (str) => {
43
  }
44
 
45
  app.all('/', async (req, res) => {
46
- if (req.method !== 'POST') return res
47
- .status(405)
48
- .json({ msg: 'Hello World' })
 
49
 
50
- const { file } = req.body
51
- if (!isBase64(file)) return res
52
- .status(400)
53
- .json({ msg: 'Bad Request' })
 
 
 
54
 
55
- const buffer = Buffer.from(file, 'base64')
56
- const type = await fileTypeFromBuffer(buffer) ||
57
- { mime: 'file', ext: 'bin' }
 
 
 
 
58
 
59
- const name = format(
60
- '%s/%s-%s.%s',
61
- tmpDir,
62
- type.mime.split('/')[0],
63
- Math.random().toString(36).slice(2),
64
- type.ext
65
- )
66
- await writeFile(name, buffer)
67
-
68
- const bytes = buffer.length
69
- res.json({
70
- name: name.split('/').pop(),
71
- size: {
72
- bytes,
73
- readable: formatBytes(
74
  bytes,
75
- { unitSeparator: ' ' }
 
 
 
 
 
 
 
 
76
  )
77
- },
78
- type,
79
- url: format(
80
- '%s://%s',
81
- req.protocol,
82
- env.SPACE_HOST + name
83
- )
84
- })
 
 
85
  }
86
 
87
  const executablePath = env.CHROME_BIN
 
43
  }
44
 
45
  app.all('/', async (req, res) => {
46
+ try {
47
+ if (req.method !== 'POST') return res
48
+ .status(405)
49
+ .json({ msg: 'Hello World' })
50
 
51
+ const { file } = req.body
52
+ if (!isBase64(file)) return res
53
+ .status(400)
54
+ .json({
55
+ err: true,
56
+ msg: 'Bad Request'
57
+ })
58
 
59
+ const buffer = Buffer.from(file, 'base64')
60
+ const type =
61
+ await fileTypeFromBuffer(buffer) ||
62
+ {
63
+ mime: 'application/octet-stream',
64
+ ext: 'bin'
65
+ }
66
 
67
+ const name = format(
68
+ '%s/%s-%s.%s',
69
+ tmpDir,
70
+ type.mime.split('/')[0],
71
+ Math.random().toString(36).slice(2),
72
+ type.ext
73
+ )
74
+ await writeFile(name, buffer)
75
+
76
+ const bytes = buffer.length
77
+ res.json({
78
+ name: name.split('/').pop(),
79
+ size: {
 
 
80
  bytes,
81
+ readable: formatBytes(
82
+ bytes,
83
+ { unitSeparator: ' ' }
84
+ ),
85
+ },
86
+ url: format(
87
+ '%s://%s',
88
+ req.protocol,
89
+ env.SPACE_HOST + name
90
  )
91
+ })
92
+ } catch (e) {
93
+ console.error(e)
94
+ res
95
+ .status(500)
96
+ .json({
97
+ err: true,
98
+ msg: format(e?.message || e)
99
+ })
100
+ }
101
  }
102
 
103
  const executablePath = env.CHROME_BIN