mealie/frontend/composables/use-validators.ts
Hayden fcc5d99d40
chore: frontend testing setup (#1739)
* add vitest

* initialize lib w/ tests

* move to dev dep

* run tests in CI

* update file names

* move api folder to lib

* move api and api types to same folder

* update generator outpath

* rm husky

* i guess i _did_ need those types

* reorg types

* extract validators into testable components

* (WIP) start composable testing

* fix import type

* fix linter complaint

* simplify icon type def

* fix linter errors (maybe?)

* rename client file for sorting
2022-10-22 11:51:07 -08:00

43 lines
1.1 KiB
TypeScript

import { ref, Ref } from "@nuxtjs/composition-api";
import { RequestResponse } from "~/lib/api/types/non-generated";
import { ValidationResponse } from "~/lib/api/types/response";
import { required, email, whitespace, url, minLength, maxLength } from "~/lib/validators";
export const validators = {
required,
email,
whitespace,
url,
minLength,
maxLength,
};
/**
* useAsyncValidator us a factory function that returns an async function that
* when called will validate the input against the backend database and set the
* error messages when applicable to the ref.
*/
export const useAsyncValidator = (
value: Ref<string>,
validatorFunc: (v: string) => Promise<RequestResponse<ValidationResponse>>,
validatorMessage: string,
errorMessages: Ref<string[]>
) => {
const valid = ref(false);
const validate = async () => {
errorMessages.value = [];
const { data } = await validatorFunc(value.value);
if (!data?.valid) {
valid.value = false;
errorMessages.value.push(validatorMessage);
return;
}
valid.value = true;
};
return { validate, valid };
};