Skip to content
This repository has been archived by the owner on Nov 16, 2020. It is now read-only.

Cache date formatters during a single template render operation. #51

Merged
merged 2 commits into from
Apr 25, 2019
Merged
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
32 changes: 28 additions & 4 deletions Sources/TemplateKit/Tag/DateFormat.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,19 +15,43 @@ public final class DateFormat: TagRenderer {
default: throw tag.error(reason: "Invalid parameter count: \(tag.parameters.count). 1 or 2 required.")
}

let formatter = DateFormatter()
/// Expect the date to be a floating point number.
guard let timestamp = tag.parameters[0].double
else { return Future.map(on: tag) { .null } }
let date = Date(timeIntervalSince1970: timestamp)

let dateFormatterCache: DateFormatterCache
if let cache = tag.context.userInfo[DateFormatterCache.userInfoKey] as? DateFormatterCache {
dateFormatterCache = cache
} else {
dateFormatterCache = DateFormatterCache()
tag.context.userInfo[DateFormatterCache.userInfoKey] = dateFormatterCache
}

let dateFormat: String
/// Set format as the second param or default to ISO-8601 format.
if tag.parameters.count == 2, let param = tag.parameters[1].string {
formatter.dateFormat = param
dateFormat = param
} else {
dateFormat = "yyyy-MM-dd HH:mm:ss"
}

let dateFormatter: DateFormatter
if let formatter = dateFormatterCache.dateFormatters[dateFormat] {
dateFormatter = formatter
} else {
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
dateFormatter = DateFormatter()
dateFormatter.dateFormat = dateFormat
dateFormatterCache.dateFormatters[dateFormat] = dateFormatter
}

/// Return formatted date
return Future.map(on: tag) { .string(formatter.string(from: date)) }
return Future.map(on: tag) { .string(dateFormatter.string(from: date)) }
}
}

private class DateFormatterCache {
static let userInfoKey = "TemplateKit.DateFormatterCache"

var dateFormatters: [String: DateFormatter] = [:]
}