-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
83 lines (72 loc) · 2.66 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
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
const express = require('express');
const path = require('path');
const cors = require('cors');
const fetch = require('node-fetch');
const app = express();
const PORT = 3000;
const CONTENTFUL_SPACE_ID = process.env.CONTENTFUL_SPACE_ID;
const CONTENTFUL_ACCESS_TOKEN = process.env.CONTENTFUL_ACCESS_TOKEN;
const COUNTERAPI_AUTHKEY = process.env.COUNTERAPI_AUTHKEY;
app.use(cors());
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
app.get('/:id', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'post.html'));
});
app.get('/api/views/:postId', async (req, res) => {
const postId = req.params.postId;
const apiUrl = `https://counter.sipped.org/punch/sippedblog/${COUNTERAPI_AUTHKEY}/${postId}`;
try {
const response = await fetch(apiUrl);
const data = await response.json();
res.json(data);
} catch (err) {
console.error('Ersror fetching view count:', err.message);
res.status(500).json({
error: 'Error fetching view count',
details: err.message,
count: 0
});
}
});
app.get('/api/posts', async (req, res) => {
const apiUrl = `https://cdn.contentful.com/spaces/${CONTENTFUL_SPACE_ID}/entries?access_token=${CONTENTFUL_ACCESS_TOKEN}&content_type=post`;
try {
const response = await fetch(apiUrl);
const data = await response.json();
res.json(data);
} catch (err) {
console.error('Error fetching posts:', err);
res.status(500).json({ error: 'Error fetching posts' });
}
});
app.get('/api/posts/:postId', async (req, res) => {
const postId = req.params.postId;
const apiUrl = `https://cdn.contentful.com/spaces/${CONTENTFUL_SPACE_ID}/entries/${postId}?access_token=${CONTENTFUL_ACCESS_TOKEN}&include=3`;
try {
const response = await fetch(apiUrl);
const data = await response.json();
res.json(data);
} catch (err) {
console.error('Error fetching post:', err);
res.status(500).json({ error: 'Error fetching post' });
}
});
app.get('/api/assets/:assetId', async (req, res) => {
const assetId = req.params.assetId;
const apiUrl = `https://cdn.contentful.com/spaces/${CONTENTFUL_SPACE_ID}/assets/${assetId}?access_token=${CONTENTFUL_ACCESS_TOKEN}`;
try {
const response = await fetch(apiUrl);
const data = await response.json();
res.json(data);
} catch (err) {
console.error('Error fetching asset:', err);
res.status(500).json({ error: 'Error fetching asset' });
}
});
module.exports = app;
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});