-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
52 lines (47 loc) · 1.84 KB
/
server.js
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
require('dotenv').config();
const express = require('express')
const path = require('path')
const socketIO = require('socket.io');
const PORT = process.env.PORT || 5000
const fetch = require('node-fetch-commonjs');
// start the express server with the appropriate routes for our webhook and web requests
var app = express()
.use(express.static(path.join(__dirname, 'public')))
.use(express.json())
.post('/alchemyhook', (req, res) => { notificationReceived(req); res.status(200).end() })
.get('/*', (req, res) => res.sendFile(path.join(__dirname + '/index.html')))
.listen(PORT, () => console.log(`Listening on ${PORT}`))
// start the websocket server
const io = socketIO(app);
// listen for client connections/calls on the WebSocket server
io.on('connection', (socket) => {
console.log('Client connected');
socket.on('disconnect', () => console.log('Client disconnected'));
socket.on('register address', (msg) => {
//send address to Alchemy to add to notification
addAddress(msg);
});
});
// notification received from Alchemy from the webhook. Let the clients know.
function notificationReceived(req) {
console.log("notification received!");
io.emit('notification', JSON.stringify(req.body));
}
// add an address to a notification in Alchemy
async function addAddress(new_address) {
console.log("adding address " + new_address);
const body = { webhook_id: process.env.ALCHEMY_WEBHOOK_ID, addresses_to_add: [new_address], addresses_to_remove: [] };
try {
fetch('https://dashboard.alchemyapi.io/api/update-webhook-addresses', {
method: 'PATCH',
body: JSON.stringify(body),
headers: { 'Content-Type': 'application/json' },
headers: { 'X-Alchemy-Token': process.env.ALCHEMY_AUTH_TOKEN }
})
.then(res => res.json())
.then(json => console.log(json));
}
catch (err) {
console.error(err);
}
}