-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
145 lines (115 loc) · 4.81 KB
/
server.js
File metadata and controls
145 lines (115 loc) · 4.81 KB
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
/**
* This is the main Node.js server script for your project
* Check out the two endpoints this back-end API provides in fastify.get and fastify.post below
*/
const path = require("path");
const fetch = require('node-fetch');
// Require the fastify framework and instantiate it
const fastify = require("fastify")({
// Set this to true for detailed logging:
logger: false,
});
// ADD FAVORITES ARRAY VARIABLE FROM TODO HERE
// Setup our static files
fastify.register(require("@fastify/static"), {
root: path.join(__dirname, "public"),
prefix: "/", // optional: default '/'
});
// Formbody lets us parse incoming forms
fastify.register(require("@fastify/formbody"));
// View is a templating manager for fastify
fastify.register(require("@fastify/view"), {
engine: {
handlebars: require("handlebars"),
},
});
// Load and parse SEO data
const seo = require("./src/seo.json");
if (seo.url === "glitch-default") {
seo.url = `https://${process.env.PROJECT_DOMAIN}.glitch.me`;
}
/**
* Our home page route
*
* Returns src/pages/index.hbs with data built into it
*/
fastify.get("/", function (request, reply) {
// params is an object we'll pass to our handlebars template
let params = { seo: seo };
// The Handlebars code will be able to access the parameter values and build them into the page
return reply.view("/src/pages/index.hbs", params);
});
fastify.get("/about", function (request, reply) {
// params is an object we'll pass to our handlebars template
let params = { seo: seo };
// The Handlebars code will be able to access the parameter values and build them into the page
return reply.view("/src/pages/about.hbs", params);
});
fastify.get("/load", async function(request, reply) {
let collectionUrl = request.query.url;
let urlPattern = /\/\/archive.org\/details\/([^\/]+)\/?$/;
let collectionName = collectionUrl.match(urlPattern)[1];
const data = await(await fetch(`https://archive.org/advancedsearch.php?q=collection%3A(${collectionName})&fl[]=[identifier]&sort[]=&sort[]=&sort[]=&rows=1&page=1&output=json`)).json();
const maxPage = await data.response.numFound;
const randomPage = (Math.floor(Math.random() * maxPage) + 1) % 10000;
const itemListing = await(await fetch(`https://archive.org/advancedsearch.php?q=collection%3A(${collectionName})&fl[identifier]=&sort[]=&sort[]=&sort[]=&rows=1&page=${randomPage}&output=json`)).json();
reply.send(await(await fetch(`https://archive.org/metadata/${itemListing.response.docs[0].identifier}`)).json());
});
fastify.get("/redirect", async function(request, reply) {
let collectionUrl = request.query.url;
console.log(collectionUrl);
let urlPattern = /\/\/archive.org\/details\/([^\/]+)\/?$/;
let collectionName = collectionUrl.match(urlPattern)[1];
const data = await(await fetch(`https://archive.org/advancedsearch.php?q=collection%3A(${collectionName})&fl[]=[identifier]&sort[]=&sort[]=&sort[]=&rows=1&page=1&output=json`)).json();
const maxPage = await data.response.numFound;
const randomPage = (Math.floor(Math.random() * maxPage) + 1) % 10000;
const itemListing = await(await fetch(`https://archive.org/advancedsearch.php?q=collection%3A(${collectionName})&fl[identifier]=&sort[]=&sort[]=&sort[]=&rows=1&page=${randomPage}&output=json`)).json();
reply.redirect(303, `https://archive.org/details/${itemListing.response.docs[0].identifier}`);
});
/**
* Our POST route to handle and react to form submissions
*
* Accepts body data indicating the user choice
*/
fastify.post("/", function (request, reply) {
// Build the params object to pass to the template
let params = { seo: seo };
// If the user submitted a color through the form it'll be passed here in the request body
let color = request.body.color;
// If it's not empty, let's try to find the color
if (color) {
// ADD CODE FROM TODO HERE TO SAVE SUBMITTED FAVORITES
// Load our color data file
const colors = require("./src/colors.json");
// Take our form submission, remove whitespace, and convert to lowercase
color = color.toLowerCase().replace(/\s/g, "");
// Now we see if that color is a key in our colors object
if (colors[color]) {
// Found one!
params = {
color: colors[color],
colorError: null,
seo: seo,
};
} else {
// No luck! Return the user value as the error property
params = {
colorError: request.body.color,
seo: seo,
};
}
}
// The Handlebars template will use the parameter values to update the page with the chosen color
return reply.view("/src/pages/index.hbs", params);
});
// Run the server and report out to the logs
fastify.listen(
{ port: process.env.PORT, host: "0.0.0.0" },
function (err, address) {
if (err) {
console.error(err);
process.exit(1);
}
console.log(`Your app is listening on ${address}`);
}
);