Skip to content

Commit

Permalink
chore(gatsby): Cache date formatting in lmdb cache (#34834)
Browse files Browse the repository at this point in the history
Co-authored-by: Michal Piechowiak <misiek.piechowiak@gmail.com>
Co-authored-by: gatsbybot <mathews.kyle+gatsbybot@gmail.com>
  • Loading branch information
3 people authored Feb 22, 2022
1 parent d4f0cef commit 446f9ff
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 7 deletions.
7 changes: 7 additions & 0 deletions packages/gatsby/src/query/__tests__/data-tracking.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,13 @@ jest.mock(`fs-extra`, () => {
}
})

jest.mock(`gatsby-telemetry`, () => {
return {
trackCli: () => {},
captureEvent: () => {},
}
})

jest.mock(`../../utils/cache-lmdb`, () => {
return {
default: class MockedCache {
Expand Down
43 changes: 36 additions & 7 deletions packages/gatsby/src/schema/types/date.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import moment, { MomentInput, unitOfTime, LocaleSpecifier } from "moment"
import { GraphQLScalarType, Kind, GraphQLFieldConfig } from "graphql"
import { oneLine } from "common-tags"
import GatsbyCacheLmdb from "../../utils/cache-lmdb"

interface IFormatDateArgs {
date: Date | string
Expand Down Expand Up @@ -209,19 +210,40 @@ export function isDate(value: MomentInput): boolean {
return typeof value !== `number` && momentDate.isValid()
}

const formatDate = ({
let formatDateCache: GatsbyCacheLmdb | undefined
function getFormatDateCache(): GatsbyCacheLmdb {
if (!formatDateCache) {
formatDateCache = new GatsbyCacheLmdb({
name: `format-date-cache`,
encoding: `string`,
}).init()
}
return formatDateCache
}

const formatDate = async ({
date,
fromNow,
difference,
formatString,
locale = `en`,
}: IFormatDateArgs): string | number => {
}: IFormatDateArgs): Promise<string | number> => {
const normalizedDate = JSON.parse(JSON.stringify(date))
if (formatString) {
return moment
const cacheKey = `${normalizedDate}-${formatString}-${locale}`
const cachedFormat = await getFormatDateCache().get(cacheKey)
if (cachedFormat) {
return cachedFormat as string
}

const result = moment
.utc(normalizedDate, ISO_8601_FORMAT, true)
.locale(locale)
.format(formatString)

await getFormatDateCache().set(cacheKey, result)

return result
} else if (fromNow) {
return moment
.utc(normalizedDate, ISO_8601_FORMAT, true)
Expand Down Expand Up @@ -282,11 +304,18 @@ export const getDateResolver = (
from: options.from || info.from,
fromNode: options.from ? options.fromNode : info.fromNode,
})
if (date == null) return null

return Array.isArray(date)
? date.map(d => formatDate({ date: d, ...args }))
: formatDate({ date, ...args })
if (date == null) {
return null
}

if (Array.isArray(date)) {
return await Promise.all(
date.map(d => formatDate({ date: d, ...args }))
)
}

return await formatDate({ date, ...args })
},
}
}

0 comments on commit 446f9ff

Please sign in to comment.