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

Add caching by Map data structure #23

Merged
merged 1 commit into from
Aug 2, 2022
Merged
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
12 changes: 12 additions & 0 deletions backend/routes/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,20 @@ const router = express.Router();

const modifyLink = require('../services/modifyLink');

const cachedResult = new Map();

router.get('/', async (req, res) => {
try {
const url = urlencode.decode(req.query.url);
if (!url) return res.status(400).end('URL을 파라미터에 포함해야 합니다.');
if (!isUrl(url)) return res.status(400).end('잘못된 형식의 URL입니다.');

// cache hit
if (cachedResult.get(url)) {
return res.end(cachedResult.get(url));
}

// cache miss
const result = await axios.get(url, {
headers: {
connection: 'keep-alive',
Expand All @@ -22,7 +31,10 @@ router.get('/', async (req, res) => {
const html = result.data;
if (!html) return res.status(404).end('HTML을 받아오지 못했습니다.');

// caching
const modified_html = modifyLink(url, html);
cachedResult.set(url, modified_html);

return res.end(modified_html);
} catch (e) {
return res.status(500).end('알 수 없는 오류가 발생했습니다.');
Expand Down