This repository has been archived by the owner on May 20, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 10
/
app.js
executable file
·175 lines (140 loc) · 4.64 KB
/
app.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
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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
"use strict";
/**
* Module dependencies.
*/
const Prismic = require('@prismicio/client');
const PrismicDOM = require('prismic-dom');
const app = require('./config');
const PrismicConfig = require('./prismic-configuration');
const asyncHandler = require ("./utils/async-handler");
const PORT = app.get('port');
function render404(req, res) {
res.status(404);
res.render("./error_handlers/404");
}
app.listen(PORT, () => {
process.stdout.write(`Point your browser to: http://localhost:${PORT}\n`);
});
// Middleware to inject prismic context
app.use((req, res, next) => {
res.locals.ctx = {
endpoint: PrismicConfig.apiEndpoint,
snipcartKey: PrismicConfig.snipcartKey,
linkResolver: PrismicConfig.linkResolver
};
// add PrismicDOM in locals to access them in templates.
res.locals.PrismicDOM = PrismicDOM;
Prismic.getApi(PrismicConfig.apiEndpoint,{ accessToken: PrismicConfig.accessToken, req: req })
.then((api) => {
req.prismic = { api };
next();
}).catch(function(err) {
if (err.status == 404) {
res.status(404).send('There was a problem connecting to your API, please check your configuration file for errors.');
} else {
res.status(500).send('Error 500: ' + err.message);
}
});
});
// Query the site layout with every route
app.route('*').get((req, res, next) => {
req.prismic.api.getSingle('layout').then(function(layoutContent){
// Give an error if no layout custom type is found
if (!layoutContent) {
res.status(500).send('No Layout document was found.');
}
// Define the layout content
res.locals.layoutContent = layoutContent;
next();
});
});
/*
* -------------- Routes --------------
*/
/*
* Preconfigured prismic preview
*/
// Prismic preview route
app.get('/preview', asyncHandler(async (req, res, next) => {
const { token, documentId } = req.query;
if(token){
try{
const redirectUrl = (await req.prismic.api.getPreviewResolver(token, documentId).resolve(PrismicConfig.linkResolver, '/'));
res.redirect(302, redirectUrl);
}catch(e){
res.status(500).send(`Error 500 in preview`);
}
}else{
res.send(400, 'Missing token from querystring');
}
next();
}))
/*
* Route for the product pages
*/
app.route('/product/:uid').get(function(req, res) {
// Get the page url needed for snipcart
var pageUrl = req.protocol + '://' + req.get('host') + req.originalUrl;
// Define the UID from the url
var uid = req.params.uid;
// Query the product by its UID
req.prismic.api.getByUID('product', uid).then(function(productContent) {
// Render the 404 page if this uid is found
if (!productContent) {
render404(req, res);
}
// Collect all the related product IDs for this product
var relatedProducts = productContent.data.relatedProducts;
var relatedIDs = relatedProducts.map((relatedProduct) => {
var link = relatedProduct.link;
return link ? link.id : null;
}).filter((id) => id !== null && id !== undefined);
//Query the related products by their IDs
req.prismic.api.getByIDs(relatedIDs).then(function(relatedProducts) {
// Render the product page
res.render('product', {
productContent: productContent,
relatedProducts: relatedProducts,
pageUrl: pageUrl
});
});
});
});
// Route for categories
app.route('/category/:uid').get(function(req, res) {
// Define the UID from the url
var uid = req.params.uid;
// Query the category by its UID
req.prismic.api.getByUID('category', uid).then(function(category) {
// Render the 404 page if this uid is found
if (!category) {
render404(req, res);
}
// Define the category ID
var categoryID = category.id;
// Query all the products linked to the given category ID
req.prismic.api.query([
Prismic.Predicates.at('document.type', 'product'),
Prismic.Predicates.at('my.product.categories.link', categoryID)
], { orderings : '[my.product.date desc]'}
).then(function(products) {
// Render the listing page
res.render('listing', {products: products.results});
});
});
});
// Route for the homepage
app.route('/').get(function(req, res) {
// Query all the products and order by their dates
req.prismic.api.query(
Prismic.Predicates.at('document.type', 'product'),
{ orderings : '[my.product.date desc]'}
).then(function(products) {
// Render the listing page
res.render('listing', {products: products.results});
});
});
// Route that catches any other url and renders the 404 page
app.route('/:url').get(function(req, res) {
render404(req, res);
});