Skip to content

Instantly share code, notes, and snippets.

@lucacicada
Last active June 6, 2023 20:39
Show Gist options
  • Save lucacicada/dd041a528261f66fab9cb873e8b9bb3c to your computer and use it in GitHub Desktop.
Save lucacicada/dd041a528261f66fab9cb873e8b9bb3c to your computer and use it in GitHub Desktop.
Nuxt v3.5.0 Decimal.js payload plugin
// plugins/decimal-payload.ts
import { Decimal } from 'decimal.js'
export default definePayloadPlugin(() => {
definePayloadReducer('Decimal', data => Decimal.isDecimal(data) && data.toJSON())
definePayloadReviver('Decimal', data => new Decimal(data))
})

Nuxt v3.5.0 Decimal.js payload plugin

Create a file named plugins/decimal-payload.ts and copy+paste the code.

Explaination

The definePayloadReducer function is invoked for each nested object. In JavaScript, the && operator evaluates the expression and returns the rightmost truthy value. Decimal.isDecimal(data) evaluates to false when false, otherwise the expression continues and returns the value data.toJSON().

definePayloadReviver is easier to understand, data is what you have return from the previous function, any value you return gonna be used in it's place instead.

The official documentation:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment