|
1 | 1 | import moment, { MomentInput, unitOfTime, LocaleSpecifier } from "moment"
|
2 | 2 | import { GraphQLScalarType, Kind, GraphQLFieldConfig } from "graphql"
|
3 | 3 | import { oneLine } from "common-tags"
|
| 4 | +import GatsbyCacheLmdb from "../../utils/cache-lmdb" |
4 | 5 |
|
5 | 6 | interface IFormatDateArgs {
|
6 | 7 | date: Date | string
|
@@ -209,19 +210,40 @@ export function isDate(value: MomentInput): boolean {
|
209 | 210 | return typeof value !== `number` && momentDate.isValid()
|
210 | 211 | }
|
211 | 212 |
|
212 |
| -const formatDate = ({ |
| 213 | +let formatDateCache: GatsbyCacheLmdb | undefined |
| 214 | +function getFormatDateCache(): GatsbyCacheLmdb { |
| 215 | + if (!formatDateCache) { |
| 216 | + formatDateCache = new GatsbyCacheLmdb({ |
| 217 | + name: `format-date-cache`, |
| 218 | + encoding: `string`, |
| 219 | + }).init() |
| 220 | + } |
| 221 | + return formatDateCache |
| 222 | +} |
| 223 | + |
| 224 | +const formatDate = async ({ |
213 | 225 | date,
|
214 | 226 | fromNow,
|
215 | 227 | difference,
|
216 | 228 | formatString,
|
217 | 229 | locale = `en`,
|
218 |
| -}: IFormatDateArgs): string | number => { |
| 230 | +}: IFormatDateArgs): Promise<string | number> => { |
219 | 231 | const normalizedDate = JSON.parse(JSON.stringify(date))
|
220 | 232 | if (formatString) {
|
221 |
| - return moment |
| 233 | + const cacheKey = `${normalizedDate}-${formatString}-${locale}` |
| 234 | + const cachedFormat = await getFormatDateCache().get(cacheKey) |
| 235 | + if (cachedFormat) { |
| 236 | + return cachedFormat as string |
| 237 | + } |
| 238 | + |
| 239 | + const result = moment |
222 | 240 | .utc(normalizedDate, ISO_8601_FORMAT, true)
|
223 | 241 | .locale(locale)
|
224 | 242 | .format(formatString)
|
| 243 | + |
| 244 | + await getFormatDateCache().set(cacheKey, result) |
| 245 | + |
| 246 | + return result |
225 | 247 | } else if (fromNow) {
|
226 | 248 | return moment
|
227 | 249 | .utc(normalizedDate, ISO_8601_FORMAT, true)
|
@@ -282,11 +304,18 @@ export const getDateResolver = (
|
282 | 304 | from: options.from || info.from,
|
283 | 305 | fromNode: options.from ? options.fromNode : info.fromNode,
|
284 | 306 | })
|
285 |
| - if (date == null) return null |
286 | 307 |
|
287 |
| - return Array.isArray(date) |
288 |
| - ? date.map(d => formatDate({ date: d, ...args })) |
289 |
| - : formatDate({ date, ...args }) |
| 308 | + if (date == null) { |
| 309 | + return null |
| 310 | + } |
| 311 | + |
| 312 | + if (Array.isArray(date)) { |
| 313 | + return await Promise.all( |
| 314 | + date.map(d => formatDate({ date: d, ...args })) |
| 315 | + ) |
| 316 | + } |
| 317 | + |
| 318 | + return await formatDate({ date, ...args }) |
290 | 319 | },
|
291 | 320 | }
|
292 | 321 | }
|
0 commit comments