@injectCurrentDatetime Directive
When building APIs, we often have to deal with dateTime to store information about when a record was created or updated. A lot of ORMs make it a standard to create createdAt
and updatedAt
fields on every table. You could also add deletedAt
to implement soft deletes.
If you're already familiar with WunderGraph, you might know that we're supporting a rich set of Database Management Systems that you can directly connect to WG. Amongst them are PostgreSQL, MySQL, SQLite, SQLServer and Planetscale.
When dealing with date and time, we've realised that not all upstreams are capable of creating these values themselves, so we've had to come up with a solution where these fields can be handled in front of the database or API.
Our solution to the problem is the @injectCurrentDateTime directive. Attach it to a field and WunderGraph automatically injects the current dateTime into the variable.
Additionally, by attaching the directive to a variable, the variable is removed from the input variables the user is allowed to supply. So, the user is no longer allowed to supply the variable, it's completely server-side generated.
By default, the dateTime String is formatted using the ISO 8601
definition, this can be adjusted.
Let's look at an example:
We might also want to be able to update the record later:
You might want to use a different format:
Here's a list of all available formats:
If your desired format is not on the list, you can also use a custom one:
Injecting a datetime into a field
@injectCurrentDateTime
accepts a second optional on:
argument that might be used to inject a value into an specific field. Given the following type:
We can use @injectCurrentDateTime
to set the value of createdAt
using:
Injecting multiple values
@injectCurrentDateTime
can be used multiple times on the same operation, injecting data into different fields. Additionally, @injectCurrentDateTime
can be combined with other directives for injecting or manipulating data like @fromClaim
, @injectEnvironmentVariable
, @injectGeneratedUUID
and @jsonSchema
.