Skip to content

Commit

Permalink
fix: single instance codec (#55)
Browse files Browse the repository at this point in the history
**Motivation**
- Right now every time we call `encode()` or `decode()`, a new codec is returned, it also create other codecs of internal fields

**Description**
- Generate the `codec()` function using single instance pattern

part of #51
  • Loading branch information
twoeths authored Aug 4, 2022
1 parent 8991c51 commit 66d9387
Showing 1 changed file with 3 additions and 1 deletion.
4 changes: 3 additions & 1 deletion packages/protons/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -190,8 +190,9 @@ export interface ${messageDef.name} {
}
}`
interfaceCodecDef = `
let _codec: Codec<${messageDef.name}>
export const codec = (): Codec<${messageDef.name}> => {
return message<${messageDef.name}>({
if (!_codec) _codec = message<${messageDef.name}>({
${Object.entries(fields)
.map(([name, fieldDef]) => {
let codec = encoders[fieldDef.type]
Expand All @@ -214,6 +215,7 @@ export interface ${messageDef.name} {
return `${fieldDef.id}: { name: '${name}', codec: ${codec}${fieldDef.options?.proto3_optional === true ? ', optional: true' : ''}${fieldDef.rule === 'repeated' ? ', repeats: true' : ''} }`
}).join(',\n ')}
})
return _codec
}
export const encode = (obj: ${messageDef.name}): Uint8ArrayList => {
Expand Down

0 comments on commit 66d9387

Please sign in to comment.