refactor(composable): mutualized computedCatch

This commit is contained in:
Corentin Thomasset 2023-11-01 10:53:05 +01:00
parent e43abeeddf
commit dfdbd30f5b
No known key found for this signature in database
GPG key ID: DBD997E935996158
2 changed files with 27 additions and 12 deletions

View file

@ -0,0 +1,22 @@
import { type Ref, ref, watchEffect } from 'vue';
export { computedCatch };
function computedCatch<T, D>(getter: () => T, { defaultValue }: { defaultValue: D; defaultErrorMessage?: string }): [Ref<T | D>, Ref<string | undefined>];
function computedCatch<T, D>(getter: () => T, { defaultValue, defaultErrorMessage = 'Unknown error' }: { defaultValue?: D; defaultErrorMessage?: string } = {}) {
const error = ref<string | undefined>();
const value = ref<T | D | undefined>();
watchEffect(() => {
try {
error.value = undefined;
value.value = getter();
}
catch (err) {
error.value = err instanceof Error ? err.message : err?.toString() ?? defaultErrorMessage;
value.value = defaultValue;
}
});
return [value, error] as const;
}

View file

@ -1,5 +1,6 @@
<script setup lang="ts"> <script setup lang="ts">
import { AES, RC4, Rabbit, TripleDES, enc } from 'crypto-js'; import { AES, RC4, Rabbit, TripleDES, enc } from 'crypto-js';
import { computedCatch } from '@/composable/computed/catchedComputed';
const algos = { AES, TripleDES, Rabbit, RC4 }; const algos = { AES, TripleDES, Rabbit, RC4 };
@ -11,17 +12,9 @@ const cypherOutput = computed(() => algos[cypherAlgo.value].encrypt(cypherInput.
const decryptInput = ref('U2FsdGVkX1/EC3+6P5dbbkZ3e1kQ5o2yzuU0NHTjmrKnLBEwreV489Kr0DIB+uBs'); const decryptInput = ref('U2FsdGVkX1/EC3+6P5dbbkZ3e1kQ5o2yzuU0NHTjmrKnLBEwreV489Kr0DIB+uBs');
const decryptAlgo = ref<keyof typeof algos>('AES'); const decryptAlgo = ref<keyof typeof algos>('AES');
const decryptSecret = ref('my secret key'); const decryptSecret = ref('my secret key');
const decryptError = ref<Error | null>(null); const [decryptOutput, decryptError] = computedCatch(() => algos[decryptAlgo.value].decrypt(decryptInput.value, decryptSecret.value).toString(enc.Utf8), {
const decryptOutput = ref(''); defaultValue: '',
watchEffect(() => { defaultErrorMessage: 'Unable to decrypt your text',
try {
decryptOutput.value = algos[decryptAlgo.value].decrypt(decryptInput.value, decryptSecret.value).toString(enc.Utf8);
decryptError.value = null;
}
catch (e) {
decryptOutput.value = '';
decryptError.value = e as Error;
}
}); });
</script> </script>
@ -72,7 +65,7 @@ watchEffect(() => {
/> />
</div> </div>
</div> </div>
<c-alert v-if="decryptError" type="error" mt-5> <c-alert v-if="decryptError" type="error" mt-12 title="Error while decrypting">
{{ decryptError }} {{ decryptError }}
</c-alert> </c-alert>
<c-input-text <c-input-text