|
1 | | -const url = require('url') |
2 | | -const { send, createError, sendError } = require('micro') |
| 1 | +const micro = require('micro') |
| 2 | +const SSE = require('sse') |
3 | 3 |
|
4 | | -const db = require('./db') |
5 | | -const { pushView } = require('./utils') |
| 4 | +const handler = require('./handler') |
| 5 | +const sseHandler = require('./sse') |
6 | 6 |
|
7 | | -module.exports = async function (req, res) { |
8 | | - const { pathname, query } = url.parse(req.url, /* parseQueryString */ true) |
9 | | - res.setHeader('Access-Control-Allow-Origin', '*') |
10 | | - // Send all views down if "?all" is true |
11 | | - if (String(query.all) === 'true') { |
12 | | - try { |
13 | | - const data = { |
14 | | - data: await db.getAll({ |
15 | | - pathname: pathname, |
16 | | - before: parseInt(query.before, 10), |
17 | | - after: parseInt(query.after, 10), |
18 | | - }), |
19 | | - time: Date.now() |
20 | | - } |
21 | | - send(res, 200, data) |
22 | | - return |
23 | | - } catch (err) { |
24 | | - console.log(err) |
25 | | - throw createError(500, 'Internal server error.') |
26 | | - } |
27 | | - } |
28 | | - // Check that a page is provided |
29 | | - if (pathname.length <= 1) { |
30 | | - throw createError(400, 'Please include a path to a page.') |
31 | | - } |
32 | | - if (req.method !== 'GET' && req.method !== 'POST') { |
33 | | - throw createError(400, 'Please make a GET or a POST request.') |
34 | | - } |
35 | | - const shouldIncrement = String(query.inc) !== 'false' |
36 | | - try { |
37 | | - const currentViews = await db.has(pathname) ? (await db.get(pathname)).views.length : 0 |
38 | | - // Add a view and send the total views back to the client |
39 | | - if (shouldIncrement) { |
40 | | - await pushView(pathname, { time: Date.now() }) |
41 | | - } |
42 | | - if (req.method === 'GET') { |
43 | | - send(res, 200, { views: shouldIncrement ? currentViews + 1 : currentViews }) |
44 | | - } else { |
45 | | - send(res, 200) |
46 | | - } |
47 | | - } catch (err) { |
48 | | - console.log(err) |
49 | | - throw createError(500, 'Internal server error.') |
50 | | - } |
51 | | -} |
| 7 | +const server = micro(handler) |
| 8 | +const sse = new SSE(server) |
| 9 | +sse.on('connection', sseHandler) |
| 10 | + |
| 11 | +server.listen(3000) |
0 commit comments