Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: add BigIntSupport plugin #2087

Merged
merged 1 commit into from
Oct 21, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions src/plugin/bigIntSupport/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
// eslint-disable-next-line valid-typeof
const isBigInt = num => typeof num === 'bigint'
export default (o, c, dayjs) => {
const proto = c.prototype
const parseDate = (cfg) => {
const { date } = cfg
if (isBigInt(date)) {
return Number(date)
}
return date
}

const oldParse = proto.parse
proto.parse = function (cfg) {
cfg.date = parseDate.bind(this)(cfg)
oldParse.bind(this)(cfg)
}


const oldUnix = dayjs.unix
dayjs.unix = function (timestamp) {
const ts = isBigInt(timestamp) ? Number(timestamp) : timestamp
return oldUnix(ts)
}
}
30 changes: 30 additions & 0 deletions test/plugin/bigIntSupport.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import MockDate from 'mockdate'
import moment from 'moment'
import dayjs from '../../src'
import bigIntSupport from '../../src/plugin/bigIntSupport'

dayjs.extend(bigIntSupport)

beforeEach(() => {
MockDate.set(new Date())
})

afterEach(() => {
MockDate.reset()
})

/* global BigInt */

it('Parse BigInt ts and tsms', () => {
const tsms = 1666310421101
const tsmsBig = BigInt(tsms)
const ts = 1666311003
const tsBig = BigInt(ts)
const momentTsms = moment(tsms)
const momentTs = moment.unix(ts)
expect(dayjs(tsms).valueOf()).toBe(momentTsms.valueOf())
expect(dayjs(tsms).valueOf()).toBe(dayjs(tsmsBig).valueOf())
expect(dayjs.unix(ts).valueOf()).toBe(momentTs.valueOf())
expect(dayjs.unix(tsBig).valueOf()).toBe(dayjs.unix(tsBig).valueOf())
})

11 changes: 11 additions & 0 deletions types/plugin/bigIntSupport.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { PluginFunc } from 'dayjs'

declare module 'dayjs' {
interface ConfigTypeMap {
bigIntSupport: BigInt
}
export function unix(t: BigInt): Dayjs
}

declare const plugin: PluginFunc
export = plugin