Skip to content

Instantly share code, notes, and snippets.

@shane-js
Created June 2, 2020 03:14
Show Gist options
  • Save shane-js/ed165ffb3f1487206b90f3c720765fa8 to your computer and use it in GitHub Desktop.
Save shane-js/ed165ffb3f1487206b90f3c720765fa8 to your computer and use it in GitHub Desktop.
ObjectionJS Postgres SQL Save JS Dates with JsonSchema "date-time" String Validation
import { Model } from "objection";
import _ from "lodash";
export class ExtendedObjectionModel extends Model {
// Use this instead of Objection's Model when making your models to fix the "is not a string" error you get when saving a JS date object to a psql datetime (timestamp) column.
// This is a WIP you may need to make some modifications.
// The main idea is to check those fields which we said should be "date-time" formatted strings in their model's jsonSchema before validation runs. If the field is a JS date, convert it to a string now before running real validation.
$beforeValidate(jsonSchema, json, opt) {
_.each(jsonSchema.properties, (schema, propertyName) => {
if (
schema &&
typeof schema.format !== "undefined" &&
schema.format === "date-time"
) {
const valueToValidate = json[propertyName];
if (valueToValidate !== null && _.isDate(valueToValidate)) {
json[propertyName] = valueToValidate.toISOString();
}
}
});
return jsonSchema;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment