From 12e21218bbf0dc017707ef183c9e18c9e1975cb2 Mon Sep 17 00:00:00 2001 From: hoilc Date: Sat, 29 Feb 2020 20:13:09 +0800 Subject: [PATCH] feat: add slug support for sspai author (#4116) --- docs/new-media.md | 2 +- lib/routes/sspai/author.js | 28 ++++++++++++++++++++-------- 2 files changed, 21 insertions(+), 9 deletions(-) diff --git a/docs/new-media.md b/docs/new-media.md index 9f9c101d82..bcc5c6d722 100644 --- a/docs/new-media.md +++ b/docs/new-media.md @@ -725,7 +725,7 @@ Supported sub-sites: ### 作者 - + ### 作者动态 diff --git a/lib/routes/sspai/author.js b/lib/routes/sspai/author.js index 51a0c279ac..a5f17f417b 100644 --- a/lib/routes/sspai/author.js +++ b/lib/routes/sspai/author.js @@ -1,16 +1,32 @@ const got = require('@/utils/got'); const cheerio = require('cheerio'); +async function getUserId(slug) { + const response = await got({ + method: 'get', + url: `https://sspai.com/api/v1/user/slug/info/get?slug=${slug}`, + headers: { + Referer: `https://sspai.com/u/${slug}/posts`, + }, + }); + + if (response.data.error !== 0) { + throw 'User Not Found'; + } + + return response.data.data.id; +} + module.exports = async (ctx) => { - const id = ctx.params.id; + const id = ctx.params.id.match(/^\d+$/) ? ctx.params.id : await getUserId(ctx.params.id); const api_url = `https://sspai.com/api/v1/articles?offset=0&limit=20&author_ids=${id}&include_total=false`; const resp = await got({ method: 'get', url: api_url, }); const data = resp.data.list; - let author_nickname = ''; - let author_id = 0; + const author_slug = data[0].author.slug; + const author_nickname = data[0].author.nickname; const items = await Promise.all( data.map(async (item) => { const link = `https://sspai.com/post/${item.id}`; @@ -28,10 +44,6 @@ module.exports = async (ctx) => { ctx.cache.set(key, description); } - // 将作者名称和id赋值给nickname和id - author_nickname = item.author.nickname; - author_id = item.author.id; - return { title: item.title.trim(), description: description, @@ -44,7 +56,7 @@ module.exports = async (ctx) => { ctx.state.data = { title: `${author_nickname} - 少数派作者`, - link: `https://sspai.com/user/${author_id}/posts`, + link: `https://sspai.com/u/${author_slug}/posts`, description: `${author_nickname} 更新推送 `, item: items, };