Skip to content

Commit

Permalink
fix: convert to webp using query params
Browse files Browse the repository at this point in the history
  • Loading branch information
wangshijun committed Jul 24, 2023
1 parent 8f99250 commit 5351643
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 23 deletions.
43 changes: 21 additions & 22 deletions api/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,42 +27,41 @@ app.use(express.urlencoded({ extended: true, limit: env.maxUploadSize }));

// Convert images to webp on the fly
// eslint-disable-next-line consistent-return
app.use('/uploads/:filename.webp', (req, res, next) => {
const filePath = `${req.params.filename}.webp`;
const sourcePath = path.join(env.uploadDir, req.params.filename);
app.use('/uploads/:filename', (req, res, next) => {
if (req.query.f !== 'webp') {
return next();
}

// requesting the source file
if (filePath.endsWith('.webp') === false) {
if (req.accepts('image/webp') === false) {
return next();
}

// already converted?
const destPath = path.join(env.uploadDir, filePath);
if (fs.existsSync(destPath)) {
// already webp?
if (req.params.filename.endsWith('.webp')) {
return next();
}

if (fs.existsSync(sourcePath)) {
// source already webp?
if (sourcePath.endsWith('.webp')) {
return res.sendFile(sourcePath, { maxAge: '356d', immutable: true });
}
// cannot convert to webp
const srcPath = path.join(env.uploadDir, req.params.filename);
if (['.png', '.jpg', '.jpeg'].some((ext) => srcPath.endsWith(ext)) === false) {
return next();
}

// cannot convert to webp
if (['.png', '.jpg', '.jpeg'].some((ext) => sourcePath.endsWith(ext)) === false) {
return res.sendFile(sourcePath, { maxAge: '356d', immutable: true });
}
// already converted?
const destPath = path.join(env.uploadDir, `${req.params.filename}.webp`);
if (fs.existsSync(destPath)) {
return res.sendFile(destPath, { maxAge: '356d', immutable: true });
}

// do the convert
any2webp(sourcePath, destPath)
any2webp(srcPath, destPath)
.then(() => {
logger.info(`Converted ${sourcePath} to webp`);
next();
logger.info(`Converted ${srcPath} to webp`);
res.sendFile(destPath, { maxAge: '356d', immutable: true });
})
.catch((err) => {
console.error(`Failed to convert ${sourcePath} to webp`, err);
res.sendFile(sourcePath, { maxAge: '356d', immutable: true });
console.error(`Failed to convert ${srcPath} to webp`, err);
next();
});
});

Expand Down
2 changes: 1 addition & 1 deletion api/libs/image.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ function any2webp(input, output) {
const dest = fs.createWriteStream(output);

// Handle success and error events
dest.on('finish', () => {
dest.on('close', () => {
resolve(output);
});

Expand Down

0 comments on commit 5351643

Please sign in to comment.