fix: fix search on Mastodon v3 (#1541)

fixes #1539
This commit is contained in:
Nolan Lawson 2019-09-26 05:24:20 -07:00 committed by GitHub
parent 5e150b31df
commit 2ada968439
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 36 additions and 5 deletions

View file

@ -1,8 +1,8 @@
import { get, paramsString, DEFAULT_TIMEOUT } from '../_utils/ajax' import { get, paramsString, DEFAULT_TIMEOUT } from '../_utils/ajax'
import { auth, basename } from './utils' import { auth, basename } from './utils'
export function search (instanceName, accessToken, query, resolve = true, limit = 5, signal = null) { function doSearch (version, instanceName, accessToken, query, resolve, limit, signal) {
const url = `${basename(instanceName)}/api/v1/search?` + paramsString({ const url = `${basename(instanceName)}/api/${version}/search?` + paramsString({
q: query, q: query,
resolve, resolve,
limit limit
@ -12,3 +12,29 @@ export function search (instanceName, accessToken, query, resolve = true, limit
signal signal
}) })
} }
async function doSearchV1 (instanceName, accessToken, query, resolve, limit, signal) {
const resp = await doSearch('v1', instanceName, accessToken, query, resolve, limit, signal)
resp.hashtags = resp.hashtags && resp.hashtags.map(tag => ({
name: tag,
url: `${basename(instanceName)}/tags/${tag.toLowerCase()}`,
history: []
}))
return resp
}
async function doSearchV2 (instanceName, accessToken, query, resolve, limit, signal) {
return doSearch('v2', instanceName, accessToken, query, resolve, limit, signal)
}
export async function search (instanceName, accessToken, query, resolve = true, limit = 5, signal = null) {
try {
return (await doSearchV2(instanceName, accessToken, query, resolve, limit, signal))
} catch (err) {
if (err && err.status === 404) { // fall back to old search API
return doSearchV1(instanceName, accessToken, query, resolve, limit, signal)
} else {
throw err
}
}
}

View file

@ -1,5 +1,5 @@
<SearchResult href="/tags/{hashtag}"> <SearchResult href="/tags/{hashtag.name.toLowerCase()}">
{'#' + hashtag} {'#' + hashtag.name}
</SearchResult> </SearchResult>
<style> <style>
</style> </style>
@ -10,4 +10,4 @@
SearchResult SearchResult
} }
} }
</script> </script>

View file

@ -23,6 +23,11 @@ function makeFetchOptions (method, headers, options) {
} }
async function throwErrorIfInvalidResponse (response) { async function throwErrorIfInvalidResponse (response) {
if (response.status >= 300) {
const err = new Error('Request failed: ' + response.status)
err.status = response.status
throw err
}
const json = await response.json() const json = await response.json()
if (response.status >= 200 && response.status < 300) { if (response.status >= 200 && response.status < 300) {
return json return json