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 () => {
const navigate = useNavigate()
const { form } = createForm<z.infer<typeof schema>>({
extend: validator({ schema }),
async onSubmit({ url, secret }) {
const onSetupSuccess = (id: string) => {
setSelectedEndpoint(id)
navigate('/overview')
}
const checkEndpoint = async ({
url,
secret,
}: {
url: string
secret: string
}) => {
try {
const { ok } = await ky.get(url, {
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()
setEndpointList([{ id, url, secret }, ...endpointList()])
setSelectedEndpoint(id)
navigate('/overview')
onSetupSuccess(id)
},
})
@ -74,10 +120,7 @@ export default () => {
{({ id, url }) => (
<div
class="badge badge-info flex w-full cursor-pointer items-center gap-4 py-4"
onClick={() => {
setSelectedEndpoint(id)
navigate('/overview')
}}
onClick={() => onEndpointSelect(id)}
>
{url}