Skip to content
This repository has been archived by the owner on Dec 14, 2023. It is now read-only.

Commit

Permalink
add api middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
arnaudlewis committed Dec 2, 2016
1 parent 5b06d8a commit aa3413b
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 28 deletions.
41 changes: 17 additions & 24 deletions app.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,33 +7,30 @@ var PORT = app.get('port');
var PConfig = require('./prismic-configuration');
var request = require('request');

function handleError(err, req, res) {
if (err.status == 404) {
res.status(404).send('404 not found');
} else {
res.status(500).send('Error 500: ' + err.message);
}
}

app.listen(PORT, function() {
const repoEndpoint = PConfig.apiEndpoint.replace('/api', '');
request.post(repoEndpoint + '/app/settings/onboarding/run', {});
console.log('Point your browser to: http://localhost:' + PORT);
});

/**
* initialize prismic context and api
* initialize prismic context and api in a middleware
*/
function api(req, res) {
res.locals.ctx = { // So we can use this information in the views
endpoint: PConfig.apiEndpoint,
linkResolver: PConfig.linkResolver
};
return Prismic.api(PConfig.apiEndpoint, {
accessToken: PConfig.accessToken,
req: req
});
}
app.use((req, res, next) => {
Prismic.api(PConfig.apiEndpoint,{accessToken: PConfig.accessToken, req: req})
.then((api) => {
req.prismic = {api: api};
res.locals.ctx = {
endpoint: PConfig.apiEndpoint,
snipcartKey: PConfig.snipcartKey,
linkResolver: PConfig.linkResolver
};
next();
}).catch(function(err) {
console.error('missing Prismic API Configuration')
next();
});
});

// INSERT YOUR ROUTES HERE

Expand Down Expand Up @@ -61,9 +58,5 @@ app.get('/help', function(req, res) {
* preconfigured prismic preview
*/
app.get('/preview', function(req, res) {
api(req, res).then(function(api) {
return Prismic.preview(api, PConfig.linkResolver, req, res);
}).catch(function(err) {
handleError(err, req, res);
});
return Prismic.preview(req.prismic.api, PConfig.linkResolver, req, res);
});
7 changes: 3 additions & 4 deletions views/help.pug
Original file line number Diff line number Diff line change
Expand Up @@ -91,10 +91,9 @@ body
|app.get('/page/:uid', function(req, res) {
| // We store the param uid in a variable
| var uid = req.params.uid;
| api(req, res).then(function(api) {
| // We are using the function to get a document by its uid
| return api.getByUID('#{'<your-custom-type-id>'}', uid);
| }).then(function(pageContent) {
| // We are using the function to get a document by its uid
| req.prismic.api.getByUID('#{'<your-custom-type-id>'}', uid)
| .then(function(pageContent) {
| // pageContent is a document, or null if there is no match
| res.render('page', {
| // Where 'page' is the name of your pug template file (page.pug)
Expand Down

0 comments on commit aa3413b

Please sign in to comment.