Skip to content

Commit

Permalink
🚸 Add cbor format auto detect
Browse files Browse the repository at this point in the history
  • Loading branch information
williamchong committed Jun 28, 2024
1 parent 24885cb commit e128111
Showing 1 changed file with 15 additions and 6 deletions.
21 changes: 15 additions & 6 deletions app.vue
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
<label for="cbor-value">CBOR</label>
<div>
<label for="cbor-encoding">Encoding</label>
<select id="cbor-encoding" v-model="cborEncoding">
<select @change="jsonToCbor" id="cbor-encoding" v-model="cborEncoding">
<option value="base64">base64</option>
<option value="hex">hex</option>
</select>
Expand Down Expand Up @@ -73,9 +73,15 @@ useHead({
],
})
onMounted(() => {
jsonToCbor()
})
function isBase64(input: string) {
const base64Pattern = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
return base64Pattern.test(input);
}
function isHex(input: string) {
const hexPattern = /^[0-9A-Fa-f]+$/;
return hexPattern.test(input);
}
function stringToBuffer(input: string) {
if (cborEncoding.value === 'base64') {
Expand All @@ -87,6 +93,11 @@ function stringToBuffer(input: string) {
function cborToJson() {
try {
if (isBase64(cborValue.value) && !isHex(cborValue.value)) {
cborEncoding.value = 'base64'
} else if (!isBase64(cborValue.value) && isHex(cborValue.value)) {
cborEncoding.value = 'hex'
}
const cbor = decode(stringToBuffer(cborValue.value))
jsonValue.value = JSON.stringify(cbor, null, 2)
} catch (e) {
Expand All @@ -106,8 +117,6 @@ function jsonToCbor() {
cborValue.value = (e as Error).message
}
}
watch(cborEncoding, () => jsonToCbor())
</script>

<style scoped>
Expand Down

0 comments on commit e128111

Please sign in to comment.