|
1
|
import { Table } from "docs-ui" |
|
2
|
|
|
3
|
export const metadata = { |
|
4
|
title: `${pageNumber} Big Numbers in Data Models`, |
|
5
|
} |
|
6
|
|
|
7
|
# {metadata.title} |
|
8
|
|
|
9
|
In this chapter, you'll learn what big numbers are, how Medusa stores them, and how to handle their values when you retrieve or compute them. |
|
10
|
|
|
11
|
## What is a Big Number? |
|
12
|
|
|
13
|
A big number is a numeric value that Medusa stores with high precision to avoid the rounding errors of JavaScript's floating-point numbers. Medusa uses big numbers for monetary and other precision-sensitive values, such as prices, order totals, tax amounts, and payment amounts. |
|
14
|
|
|
15
|
<Note title="Tip"> |
|
16
|
|
|
17
|
Prices in Medusa are stored as major currency units. For example, a price of $10.99 is stored as `10.99`, not `1099`. This is different from some other systems that store prices in minor currency units (for example, cents). |
|
18
|
|
|
19
|
</Note> |
|
20
|
|
|
21
|
You define a big-number property in a data model with the [bigNumber](../properties/page.mdx#bignumber) method: |
|
22
|
|
|
23
|
export const modelHighlights = [ |
|
24
|
["5", "bigNumber", "Define a `bigNumber` property."], |
|
25
|
] |
|
26
|
|
|
27
|
```ts highlights={modelHighlights} |
|
28
|
import { model } from "@medusajs/framework/utils" |
|
29
|
|
|
30
|
const CustomProduct = model.define("custom_product", { |
|
31
|
id: model.id().primaryKey(), |
|
32
|
price: model.bigNumber(), |
|
33
|
}) |
|
34
|
|
|
35
|
export default CustomProduct |
|
36
|
``` |
|
37
|
|
|
38
|
<Note title="Tip"> |
|
39
|
|
|
40
|
Use a big-number property when you need high precision for numbers that can have many decimal places. For less precision, use the [float property](../properties/page.mdx#float) instead. |
|
41
|
|
|
42
|
</Note> |
|
43
|
|
|
44
|
--- |
|
45
|
|
|
46
|
## How Medusa Stores Big Numbers |
|
47
|
|
|
48
|
For each big-number property, Medusa stores two columns in the database: |
|
49
|
|
|
50
|
- A `numeric` column with the same name as the property (for example, `price`). This holds the value as a number for convenience and querying. |
|
51
|
- A `raw_` column prefixed with the property's name (for example, `raw_price`). This holds an object with the value as a string and its precision, which is the source of truth for the precise value. |
|
52
|
|
|
53
|
For example, the `raw_price` column stores an object like this: |
|
54
|
|
|
55
|
```json title="raw_price" |
|
56
|
{ |
|
57
|
"value": "10.99", |
|
58
|
"precision": 20 |
|
59
|
} |
|
60
|
``` |
|
61
|
|
|
62
|
The `value` is a string to preserve precision, since a string doesn't lose precision the way a JavaScript number can. |
|
63
|
|
|
64
|
--- |
|
65
|
|
|
66
|
## When Does Medusa Return a Big Number Value |
|
67
|
|
|
68
|
The shape of a big-number value depends on where you retrieve it and how the value is produced. Medusa reduces the value to a plain number only when it serializes the value to JSON for an HTTP response (that is, when the data is returned from an API route). |
|
69
|
|
|
70
|
The following table summarizes the shape of a big-number value: |
|
71
|
|
|
72
|
<Table> |
|
73
|
<Table.Header> |
|
74
|
<Table.Row> |
|
75
|
<Table.HeaderCell> |
|
76
|
Where and How You Retrieve the Value |
|
77
|
</Table.HeaderCell> |
|
78
|
<Table.HeaderCell> |
|
79
|
Shape |
|
80
|
</Table.HeaderCell> |
|
81
|
</Table.Row> |
|
82
|
</Table.Header> |
|
83
|
<Table.Body> |
|
84
|
<Table.Row> |
|
85
|
<Table.Cell> |
|
86
|
|
|
87
|
Server-side code (such as `query.graph`, a workflow, or a module service), retrieving a stored `bigNumber` property directly. For example, your custom `price` property, or a payment's `amount`. |
|
88
|
|
|
89
|
</Table.Cell> |
|
90
|
<Table.Cell> |
|
91
|
|
|
92
|
A plain number. You can also request the property's `raw_` field (such as `raw_price`) to retrieve the precise value. |
|
93
|
|
|
94
|
</Table.Cell> |
|
95
|
</Table.Row> |
|
96
|
<Table.Row> |
|
97
|
<Table.Cell> |
|
98
|
|
|
99
|
Server-side code, retrieving a total that a Commerce Module computes and wraps in a `BigNumber`. For example, an order's or cart's `total` or `subtotal`. |
|
100
|
|
|
101
|
</Table.Cell> |
|
102
|
<Table.Cell> |
|
103
|
|
|
104
|
A `BigNumber` instance. |
|
105
|
|
|
106
|
</Table.Cell> |
|
107
|
</Table.Row> |
|
108
|
<Table.Row> |
|
109
|
<Table.Cell> |
|
110
|
|
|
111
|
A client consuming the response of an API route. |
|
112
|
|
|
113
|
</Table.Cell> |
|
114
|
<Table.Cell> |
|
115
|
|
|
116
|
A plain number. |
|
117
|
|
|
118
|
</Table.Cell> |
|
119
|
</Table.Row> |
|
120
|
</Table.Body> |
|
121
|
</Table> |
|
122
|
|
|
123
|
The difference in server-side code comes down to how the value is produced: |
|
124
|
|
|
125
|
- Medusa reads a stored `bigNumber` property back as its numeric value, so you get a plain number. The precise value is available in the property's `raw_` field when you request it, as explained in the next section. |
|
126
|
- Commerce Modules compute some totals, such as an order's `total`, and wrap them in a `BigNumber` instance. For example, if you retrieve an order's total with [Query](../../query/page.mdx), the `total` property is a `BigNumber` instance: |
|
127
|
|
|
128
|
```ts |
|
129
|
const { data: orders } = await query.graph({ |
|
130
|
entity: "order", |
|
131
|
fields: ["total"], |
|
132
|
}) |
|
133
|
|
|
134
|
// orders[0].total is a BigNumber instance |
|
135
|
``` |
|
136
|
|
|
137
|
<Note title="Tip"> |
|
138
|
|
|
139
|
In server-side code, don't assume whether a big-number value is a plain number or a `BigNumber` instance. Handle it as explained in the next sections, which work for both shapes. |
|
140
|
|
|
141
|
</Note> |
|
142
|
|
|
143
|
### Retrieve the Precise Value of a Stored Property |
|
144
|
|
|
145
|
By default, `query.graph` returns only the fields you request, and a stored `bigNumber` property returns a plain number. To also retrieve the precise value, add the `raw_` field to the `fields` array: |
|
146
|
|
|
147
|
export const rawHighlights = [ |
|
148
|
["3", "raw_price", "Request the precise value explicitly."], |
|
149
|
] |
|
150
|
|
|
151
|
```ts highlights={rawHighlights} |
|
152
|
const { data: products } = await query.graph({ |
|
153
|
entity: "custom_product", |
|
154
|
fields: ["price", "raw_price"], |
|
155
|
}) |
|
156
|
``` |
|
157
|
|
|
158
|
Each product now has a `raw_price` property with the precise value: |
|
159
|
|
|
160
|
```json title="Result" |
|
161
|
[ |
|
162
|
{ |
|
163
|
"price": 10.99, |
|
164
|
"raw_price": { |
|
165
|
"value": "10.99", |
|
166
|
"precision": 20 |
|
167
|
} |
|
168
|
} |
|
169
|
] |
|
170
|
``` |
|
171
|
|
|
172
|
--- |
|
173
|
|
|
174
|
## How to Handle Retrieved Big Numbers |
|
175
|
|
|
176
|
### Display a Big Number |
|
177
|
|
|
178
|
When a client consumes an API route's response, the big-number value is a plain number that you can format and display directly. |
|
179
|
|
|
180
|
In server-side code, a big-number value is either a plain number (for a stored property like `price`) or a `BigNumber` instance (for a computed total like an order's `total`). To get a plain number from either shape, check its type. If it's a `BigNumber` instance, use its `numeric` property. Otherwise, it's already a plain number, so use it as-is: |
|
181
|
|
|
182
|
```ts |
|
183
|
import { BigNumber } from "@medusajs/framework/utils" |
|
184
|
|
|
185
|
const price = |
|
186
|
customProduct.price instanceof BigNumber |
|
187
|
? customProduct.price.numeric |
|
188
|
: customProduct.price |
|
189
|
``` |
|
190
|
|
|
191
|
You can also use the value in string interpolation, since a `BigNumber` instance supports numeric coercion: |
|
192
|
|
|
193
|
```ts |
|
194
|
const message = `The price is ${customProduct.price}` |
|
195
|
``` |
|
196
|
|
|
197
|
To display a price with its currency, pass the plain number and the currency code to JavaScript's [Intl.NumberFormat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat). Medusa stores prices in major currency units, so you can format the value directly: |
|
198
|
|
|
199
|
export const formatHighlights = [ |
|
200
|
["2", "style: \"currency\"", "Format the number as a currency."], |
|
201
|
["3", "currency", "Pass the price's currency code."], |
|
202
|
] |
|
203
|
|
|
204
|
```ts highlights={formatHighlights} |
|
205
|
const formatted = new Intl.NumberFormat("en-US", { |
|
206
|
style: "currency", |
|
207
|
currency: "usd", |
|
208
|
}).format(Number(customProduct.price)) |
|
209
|
|
|
210
|
// formatted is "$10.99" |
|
211
|
``` |
|
212
|
|
|
213
|
<Note type="warning"> |
|
214
|
|
|
215
|
Don't use a big-number's plain-number value as an input to further calculations, as it can lose precision. Instead, use the `MathBN` utility explained next. |
|
216
|
|
|
217
|
</Note> |
|
218
|
|
|
219
|
### Perform Arithmetic with MathBN |
|
220
|
|
|
221
|
To perform arithmetic on big numbers without losing precision, use the `MathBN` utility from `@medusajs/framework/utils`. Don't use JavaScript's arithmetic and comparison operators, such as `+` or `>`, as they reintroduce floating-point errors. |
|
222
|
|
|
223
|
`MathBN` has the following methods for arithmetic operations: |
|
224
|
|
|
225
|
- `MathBN.add(...nums)`: Add two or more numbers. |
|
226
|
- `MathBN.sub(...nums)`: Subtract numbers from the first number. |
|
227
|
- `MathBN.mult(n1, n2)`: Multiply two numbers. |
|
228
|
- `MathBN.div(n1, n2)`: Divide the first number by the second. |
|
229
|
- `MathBN.sum(...nums)`: Add all numbers, starting from `0`. |
|
230
|
- `MathBN.abs(n)`: Get the absolute value of a number. |
|
231
|
- `MathBN.min(...nums)` and `MathBN.max(...nums)`: Get the smallest or largest number. |
|
232
|
|
|
233
|
Each method accepts big-number values in any shape, including a `BigNumber` instance, a plain number, a numeric string, or a `raw_` object. So, you can pass values retrieved from Query directly to `MathBN`. |
|
234
|
|
|
235
|
`MathBN` performs exact decimal arithmetic, so it doesn't introduce the floating-point errors that JavaScript operators do. |
|
236
|
|
|
237
|
For full precision, request and pass the `raw_` value. Query types the `raw_` field as `Record<string, unknown>`, so cast it to `BigNumberRawValue` from `@medusajs/framework/types`. You can also pass the plain number property, which is exact for typical values. |
|
238
|
|
|
239
|
For example, to add two prices: |
|
240
|
|
|
241
|
export const addHighlights = [ |
|
242
|
["10", "as BigNumberRawValue", "Cast the raw value to satisfy the type."], |
|
243
|
["9", "MathBN.add", "Add the two prices precisely."], |
|
244
|
["15", "toNumber", "Convert the result to a plain number."], |
|
245
|
] |
|
246
|
|
|
247
|
```ts highlights={addHighlights} |
|
248
|
import { MathBN } from "@medusajs/framework/utils" |
|
249
|
import { BigNumberRawValue } from "@medusajs/framework/types" |
|
250
|
|
|
251
|
const { data: products } = await query.graph({ |
|
252
|
entity: "custom_product", |
|
253
|
fields: ["price", "raw_price"], |
|
254
|
}) |
|
255
|
|
|
256
|
const total = MathBN.add( |
|
257
|
products[0].raw_price as BigNumberRawValue, |
|
258
|
products[1].raw_price as BigNumberRawValue |
|
259
|
) |
|
260
|
|
|
261
|
// use the result as a plain number |
|
262
|
const totalNumber = total.toNumber() |
|
263
|
``` |
|
264
|
|
|
265
|
A `MathBN` method returns a big-number instance from the underlying `bignumber.js` library. To use the result as a plain number, call its `toNumber` method or pass it to the `Number` function, as shown above. |
|
266
|
|
|
267
|
### Sum an Array of Big Numbers |
|
268
|
|
|
269
|
To sum an array of big-number values, use JavaScript's `reduce` method with `MathBN.sum`. Start the accumulator with `MathBN.convert(0)`, which creates a big-number `0`: |
|
270
|
|
|
271
|
export const reduceHighlights = [ |
|
272
|
["15", "MathBN.convert(0)", "Start the sum with a big-number `0`."], |
|
273
|
["11", "MathBN.sum", "Add each price to the running sum."], |
|
274
|
["13", "as BigNumberRawValue", "Cast the raw value to satisfy the type."], |
|
275
|
] |
|
276
|
|
|
277
|
```ts highlights={reduceHighlights} |
|
278
|
import { MathBN } from "@medusajs/framework/utils" |
|
279
|
import { BigNumberRawValue } from "@medusajs/framework/types" |
|
280
|
|
|
281
|
const { data: products } = await query.graph({ |
|
282
|
entity: "custom_product", |
|
283
|
fields: ["price", "raw_price"], |
|
284
|
}) |
|
285
|
|
|
286
|
const total = products.reduce( |
|
287
|
(sum, product) => |
|
288
|
MathBN.sum( |
|
289
|
sum, |
|
290
|
product.raw_price as BigNumberRawValue |
|
291
|
), |
|
292
|
MathBN.convert(0) |
|
293
|
) |
|
294
|
``` |
|
295
|
|
|
296
|
<Note title="Tip"> |
|
297
|
|
|
298
|
`MathBN.convert(value)` normalizes any big-number shape to an instance you can use in calculations. `MathBN.convert(0)` is the common way to create a big-number `0`. |
|
299
|
|
|
300
|
</Note> |
|
301
|
|
|
302
|
### Compare Big Numbers |
|
303
|
|
|
304
|
To compare big-number values, use the following `MathBN` methods, which each return a boolean: |
|
305
|
|
|
306
|
- `MathBN.gt(n1, n2)`: Whether the first number is greater than the second. |
|
307
|
- `MathBN.gte(n1, n2)`: Whether the first is greater than or equal to the second. |
|
308
|
- `MathBN.lt(n1, n2)`: Whether the first number is less than the second. |
|
309
|
- `MathBN.lte(n1, n2)`: Whether the first is less than or equal to the second. |
|
310
|
- `MathBN.eq(n1, n2)`: Whether the two numbers are equal. |
|
311
|
|
|
312
|
For example: |
|
313
|
|
|
314
|
export const compareHighlights = [ |
|
315
|
["5", "MathBN.gt", "Keep products with a price above `0`."], |
|
316
|
["6", "as BigNumberRawValue", "Cast the raw value to satisfy the type."], |
|
317
|
] |
|
318
|
|
|
319
|
```ts highlights={compareHighlights} |
|
320
|
import { BigNumberRawValue } from "@medusajs/framework/types" |
|
321
|
|
|
322
|
const pricedProducts = products.filter( |
|
323
|
(product) => |
|
324
|
MathBN.gt( |
|
325
|
product.raw_price as BigNumberRawValue, |
|
326
|
0 |
|
327
|
) |
|
328
|
) |
|
329
|
``` |
|
330
|
|
|
331
|
--- |
|
332
|
|
|
333
|
## How to Store Big Numbers in a Service |
|
334
|
|
|
335
|
When you store a big-number field with a [module service's](../../modules/page.mdx#2-create-service) generated methods, such as `createCustomProducts` or `updateCustomProducts`, pass a plain number. Medusa converts it to a big number and maintains the `raw_` column automatically. |
|
336
|
|
|
337
|
For example: |
|
338
|
|
|
339
|
```ts |
|
340
|
const customProduct = |
|
341
|
await customProductModuleService.createCustomProducts({ |
|
342
|
price: 10.99, |
|
343
|
}) |
|
344
|
``` |
|
345
|
|
|
346
|
The created record will have a `price` of `10.99` and a `raw_price` of: |
|
347
|
|
|
348
|
```json title="raw_price" |
|
349
|
{ |
|
350
|
"value": "10.99", |
|
351
|
"precision": 20 |
|
352
|
} |
|
353
|
``` |