Skip to content

Commit

Permalink
Merge pull request #162 from increments/fix-assets-api
Browse files Browse the repository at this point in the history
Fix issue that appearance of preview differs between Qiita and Qiita CLI
  • Loading branch information
ohakutsu authored Jul 16, 2024
2 parents 7856794 + 3e8f8d0 commit 3cba960
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 25 deletions.
4 changes: 4 additions & 0 deletions src/qiita-api/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -269,4 +269,8 @@ export class QiitaApi {
body: data,
});
}

async getAssetUrls() {
return await this.get<{ [key: string]: string }>("/api/qiita-cli/assets");
}
}
44 changes: 19 additions & 25 deletions src/server/api/assets.ts
Original file line number Diff line number Diff line change
@@ -1,56 +1,50 @@
import type Express from "express";
import { Router } from "express";
import { getQiitaApiInstance } from "../../lib/get-qiita-api-instance";

const redirectToArticleCss = async (
req: Express.Request,
res: Express.Response,
) => {
const url =
process.env.QIITA_ASSETS_ARTICLE_CSS ||
(await resolveAssetsUrl("public/article.css"));
const url = await resolveAssetsUrl("article_css_url");
res.redirect(url);
};

const redirectToEmbedInitJs = async (
req: Express.Request,
res: Express.Response,
) => {
const url =
process.env.QIITA_ASSETS_EMBED_INIT_JS ||
(await resolveAssetsUrl("public/v3-embed-init.js"));
const url = await resolveAssetsUrl("v3_embed_init_js_url");
res.redirect(url);
};

const redirectToFavicon = async (
req: Express.Request,
res: Express.Response,
) => {
const url =
process.env.QIITA_ASSETS_FAVICON ||
(await resolveAssetsUrl("favicons/public/production.ico"));
const url = await resolveAssetsUrl("favicon_url");
res.redirect(url);
};

const resolveAssetsUrl = async (key: string) => {
const latest_manifest_url =
"https://qiita.com/assets/.latest_client_manifest_name_production";
const resolveAssetsUrl = (() => {
let cachedAssetUrls: { [key: string]: string } | null = null;

const cdnAssetsUrl = "https://cdn.qiita.com/assets";
return async (key: string) => {
if (cachedAssetUrls === null) {
const qiitaApi = await getQiitaApiInstance();
const assetUrls = await qiitaApi.getAssetUrls();

const clientManifestFileName = await (
await fetch(latest_manifest_url)
).text();
const json = await (
await fetch(`${cdnAssetsUrl}/${clientManifestFileName}`)
).json();
cachedAssetUrls = assetUrls;
}

const filename = json[key];
if (filename === undefined) {
throw new Error(`Asset not found: ${key}`);
}
const url = cachedAssetUrls[key];
if (!url) {
throw new Error(`Asset not found: ${key}`);
}

return `${cdnAssetsUrl}/${filename}`;
};
return url;
};
})();

export const AssetsRouter = Router()
.get("/article.css", redirectToArticleCss)
Expand Down

0 comments on commit 3cba960

Please sign in to comment.