money-safe
v0.1.0TYPE-SAFE MONEY
DOCS INTERFACE · GUIDE / RECIPES / REFERENCE · MINOR UNITS STAY EXPLICIT
Database

Database

Use columns that preserve the value and its metadata:

sql
CREATE TABLE order_payments (
  id BIGINT PRIMARY KEY,
  amount_minor BIGINT NOT NULL,
  currency CHAR(3) NOT NULL,
  minor_unit SMALLINT NOT NULL,
  created_at TIMESTAMP NOT NULL
);

Read a row:

ts
const value = amount.fromJSON({
  amountMinor: row.amount_minor,
  currency: row.currency,
  minorUnit: row.minor_unit
});

Write a row:

ts
const payload = amount('19.99', 'CNY').toJSON();

const row = {
  amount_minor: payload.amountMinor,
  currency: payload.currency,
  minor_unit: payload.minorUnit
};