Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove some of the Promises in favour of async/await #10

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 24 additions & 48 deletions lib/photo-manager/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ module.exports = function createPhotoManager({photoPath, cacheDuration, paginati
});
}

function maybeUpdateData() {
async function maybeUpdateData() {
let needsUpdate;

if (lastUpdate == null) {
Expand All @@ -107,63 +107,39 @@ module.exports = function createPhotoManager({photoPath, cacheDuration, paginati
}

if (needsUpdate) {
return Promise.try(() => {
return updateData();
}).then(() => {
lastUpdate = Date.now();
});
await updateData();
lastUpdate = Date.now();
}
}

return {
getDates: function () {
return Promise.try(() => {
return maybeUpdateData();
}).then(() => {
return knownDates;
});
getDates: async function() {
await maybeUpdateData();
return knownDates;
},
getDateReferences: function (date) {
return Promise.try(() => {
return maybeUpdateData();
}).then(() => {
return dateReferenceMap.get(date);
});
getDateReferences: async function(date) {
await maybeUpdateData();
return dateReferenceMap.get(date);
},
getDatesWithPictures: function () {
return Promise.try(() => {
return maybeUpdateData();
}).then(() => {
return groupedPictures;
});
getDatesWithPictures: async function() {
await maybeUpdateData();
return groupedPictures;
},
getPaginatedDatesWithPictures: function () {
return Promise.try(() => {
return this.getDatesWithPictures();
}).then((dates) => {
return paginatedPictures;
});
getPaginatedDatesWithPictures: async function() {
let dates = await this.getDatesWithPictures();
return paginatedPictures;
},
getPicturesForDate: function (date) {
return Promise.try(() => {
return maybeUpdateData();
}).then(() => {
return knownPictures.filter((picture) => picture.date === date);
});
getPicturesForDate: async function(date) {
await maybeUpdateData();
return knownPictures.filter((picture) => picture.date === date);
},
getPictures: function () {
return Promise.try(() => {
return maybeUpdateData();
}).then(() => {
return knownPictures;
});
getPictures: async function() {
await maybeUpdateData();
return knownPictures;
},
getPicture: function (date, filename) {
return Promise.try(() => {
return maybeUpdateData();
}).then(() => {
return knownPictureMap.get(date).get(filename);
});
getPicture: async function(date, filename) {
await maybeUpdateData();
return knownPictureMap.get(date).get(filename);
}
}
};
119 changes: 55 additions & 64 deletions server.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
'use strict';

const Promise = require("bluebird");
const express = require("express");
const expressPromiseRouter = require("express-promise-router");
const path = require("path");
const fs = Promise.promisifyAll(require("fs"));
const defaultValue = require("default-value");
const unhandledError = require("unhandled-error");

Expand Down Expand Up @@ -43,88 +41,81 @@ app.use("/photos", express.static(config.pictureFolder));

let router = expressPromiseRouter();

router.get("/latest", (req, res) => {
return Promise.try(() => {
if (req.query.amount != null) {
validateNumber(req.query.amount);
}
router.get("/latest", async (req, res) => {
if (req.query.amount != null) {
validateNumber(req.query.amount);
}

return photoManager.getPictures();
}).then((pictures) => {
let amount = parseInt(defaultValue(req.query.amount, 3));

res.json({
latest: pictures.slice(0, amount).map((picture) => {
return {
date: picture.date.momentDate.format("YYYY-MM-DD"),
filename: picture.filename,
url: `${config.pathPrefix}/view/${picture.date.date}/${picture.filename}`,
thumbnail: `${config.pathPrefix}/thumbnails/${picture.date.date}/${picture.filename}`
};
})
});
let pictures = await photoManager.getPictures();

let amount = parseInt(defaultValue(req.query.amount, 3));

res.json({
latest: pictures.slice(0, amount).map((picture) => {
return {
date: picture.date.momentDate.format("YYYY-MM-DD"),
filename: picture.filename,
url: `${config.pathPrefix}/view/${picture.date.date}/${picture.filename}`,
thumbnail: `${config.pathPrefix}/thumbnails/${picture.date.date}/${picture.filename}`
};
})
});
});

router.get("/:page?", (req, res) => {
return Promise.try(() => {
if (req.params.page != null) {
validateNumber(req.params.page);
}
router.get("/:page?", async (req, res) => {
if (req.params.page != null) {
validateNumber(req.params.page);
}

return photoManager.getPaginatedDatesWithPictures();
}).then((dates) => {
let pageParam = defaultValue(req.params.page, 1);
let pageNumber = parseInt(pageParam) - 1;
let dates = await photoManager.getPaginatedDatesWithPictures();
let pageParam = defaultValue(req.params.page, 1);
let pageNumber = parseInt(pageParam) - 1;

if (pageNumber < 0 || pageNumber > dates.length - 1) {
res.status(404).send("404 not found");
} else {
res.render("index", {
dates: dates[pageNumber],
currentPage: pageNumber + 1,
totalPages: dates.length
});
}
if (pageNumber < 0 || pageNumber > dates.length - 1) {
res.status(404).send("404 not found");
return;
}

res.render("index", {
dates: dates[pageNumber],
currentPage: pageNumber + 1,
totalPages: dates.length
});
});

router.get("/view/:date/:filename", (req, res) => {
return Promise.try(() => {
validateDateFolderName(req.params.date);
validatePhotoFilename(req.params.filename);
router.get("/view/:date/:filename", async (req, res) => {
validateDateFolderName(req.params.date);
validatePhotoFilename(req.params.filename);

return photoManager.getPicture(req.params.date, req.params.filename);
}).then((photo) => {
if (photo == null) {
res.status(404).send("404 not found");
} else {
res.render("view", {
photo: photo,
previousPhoto: photo.previous,
nextPhoto: photo.next,
// NOTE: The below does not currently work when the user-facing HTTPd is running on a non-standard port!
absoluteThumbnail: `${req.protocol}://${req.host}${config.pathPrefix}/thumbnails/${photo.date.date}/${photo.filename}`
});
}
let photo = await photoManager.getPicture(req.params.date, req.params.filename);
if (photo == null) {
res.status(404).send("404 not found");
return;
}

res.render("view", {
photo: photo,
previousPhoto: photo.previous,
nextPhoto: photo.next,
// NOTE: The below does not currently work when the user-facing HTTPd is running on a non-standard port!
absoluteThumbnail: `${req.protocol}://${req.host}${config.pathPrefix}/thumbnails/${photo.date.date}/${photo.filename}`
});
});

router.get("/thumbnails/:date/:filename", (req, res) => {
return Promise.try(() => {
validateDateFolderName(req.params.date);
validatePhotoFilename(req.params.filename);
router.get("/thumbnails/:date/:filename", async (req, res) => {
validateDateFolderName(req.params.date);
validatePhotoFilename(req.params.filename);

return thumbnailer(req.params.date, req.params.filename);
}).then((stream) => {
try {
let stream = await thumbnailer(req.params.date, req.params.filename);
stream.pipe(res);
}).catch((err) => {
} catch (err) {
if (/Unable to open file/.test(err.message)) {
res.status(404).send("404 not found");
} else {
throw err;
}
});
}
});

app.use(router);
Expand Down