import { createForm } from '@felte/solid'; import { Component, createEffect, Match, Switch } from 'solid-js'; import { TextField, Button } from '@kobalte/core'; import reporter from '@felte/reporter-tippy'; import { v4 as uuid } from 'uuid'; import './style.css'; import { useNavigate } from 'solid-start'; import { adminCredentials } from '../credentials'; import { put } from '~/lib/put'; import { del } from '~/lib/del'; import { isFunction } from 'lodash'; interface Props { values?: () => any; } const User: Component = (props) => { const navigate = useNavigate(); const getValues = () => { if (!isFunction(props?.values)) { return null; } return props.values(); }; const isNew = () => !getValues(); const submitHandler = async (values: any, context: any) => { console.log({ caller: 'User / submitHandler', props, values, context, }); const id = getValues()?._id ?? `user:${uuid()}`; await put(id, values, isNew()); if (isNew()) { navigate(`/user/${id}`); } }; const cancelHandler = () => { navigate(`/user/`); }; const deleteHandler = async () => { console.log({ caller: 'User / deleteHandler', id: getValues()?._id, props, }); await del(getValues()?._id); navigate(`/user/`); }; const validationHandler = async (values: any) => { let errors: any = {}; const credentials = adminCredentials(); if (!credentials) { return errors; } const { database, username, password } = credentials; try { const response = await fetch(database, { mode: 'cors' }); const dbStatus = await response.json(); if (!dbStatus.couchdb) { errors.database = 'The URL is not a couchdb instance'; } } catch (error) { errors.database = "Can't access the database"; } if (!!errors.database) { return errors; } if (isNew()) { const authString = `${username}:${password}`; const headers = new Headers(); headers.set('Authorization', 'Basic ' + btoa(authString)); const response = await fetch( `${database}/_users/org.couchdb.user:${values.username}`, { method: 'HEAD', mode: 'cors', headers, } ); if (response.status === 200) { errors.username = 'The user is already existing'; } } return errors; }; const credentials = adminCredentials(); const { database } = credentials || { database: null }; const { form, data, setData, setInitialValues, reset } = createForm({ onSubmit: submitHandler, extend: reporter(), validate: validationHandler, initialValues: getValues() || { database }, }); const createUserHandler = async () => { console.log({ caller: 'User / createUserHandler', props, data: data(), }); // setOpenUserNamePasswordDialog(true); }; console.log({ caller: 'User ', props, values: getValues(), }); return (
Mail address Please provide a valid URL Database User name Password Save Delete Create Cancel
); }; export default User;