feat: prevent duplicate endpoints from being stored (#45)

* feat: prevent duplicate endpoints from being stored

Bonus: this commit also prevents unusable endpoint from being selected

* fix: catch checkEndpoint errors

* fix: navigation issue
This commit is contained in:
kunish 2023-08-30 17:50:28 +08:00 committed by GitHub
parent 43edb25c10
commit e96628845b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -16,9 +16,19 @@ const schema = z.object({
export default () => { export default () => {
const navigate = useNavigate() const navigate = useNavigate()
const { form } = createForm<z.infer<typeof schema>>({ const onSetupSuccess = (id: string) => {
extend: validator({ schema }), setSelectedEndpoint(id)
async onSubmit({ url, secret }) { navigate('/overview')
}
const checkEndpoint = async ({
url,
secret,
}: {
url: string
secret: string
}) => {
try {
const { ok } = await ky.get(url, { const { ok } = await ky.get(url, {
headers: secret headers: secret
? { ? {
@ -27,12 +37,48 @@ export default () => {
: {}, : {},
}) })
if (!ok) return 1 return ok
} catch {
return false
}
}
const onEndpointSelect = async (id: string) => {
const endpoint = endpointList().find((e) => e.id === id)
if (!endpoint) {
return
}
if (
!(await checkEndpoint({ url: endpoint.url, secret: endpoint.secret }))
) {
return
}
onSetupSuccess(id)
}
const { form } = createForm<z.infer<typeof schema>>({
extend: validator({ schema }),
async onSubmit({ url, secret }) {
const endpointFromHistory = endpointList().find(
(history) => history.url === url && history.secret === secret,
)
if (endpointFromHistory) {
onSetupSuccess(endpointFromHistory.id)
return
}
if (!(await checkEndpoint({ url, secret }))) {
return
}
const id = uuid() const id = uuid()
setEndpointList([{ id, url, secret }, ...endpointList()]) setEndpointList([{ id, url, secret }, ...endpointList()])
setSelectedEndpoint(id) onSetupSuccess(id)
navigate('/overview')
}, },
}) })
@ -74,10 +120,7 @@ export default () => {
{({ id, url }) => ( {({ id, url }) => (
<div <div
class="badge badge-info flex w-full cursor-pointer items-center gap-4 py-4" class="badge badge-info flex w-full cursor-pointer items-center gap-4 py-4"
onClick={() => { onClick={() => onEndpointSelect(id)}
setSelectedEndpoint(id)
navigate('/overview')
}}
> >
{url} {url}