Effect CommunityEC
Effect Community6mo ago
9 replies
technopriest

Reusing and Overriding Schema Fields in SQL Model with Model Wrappers

What is the best way to reuse a schema definition and selectively override fields with Model wrappers to create an sql model?

import { Schema } from 'effect'
import { Model } from '@effect/sql'

export const Email = Schema.NonEmptyTrimmedString.pipe(
  Schema.pattern(/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/),
  Schema.annotations({
    title: 'Email',
    description: 'An email address'
  }),
  Schema.brand('Email')
)

export type Email = typeof Email.Type

export const UserId = Schema.ULID.pipe(
  Schema.annotations({
    title: 'User Identifier',
    desciption: 'Globally unique string identifyng a user.'
  }),
  Schema.pattern(/^user_[0-9A-HJ-NP-TV-Z]{26}$/i),
  Schema.brand('UserId')
)

export const User = Schema.Struct({
  id: Schema.String,
  email: Email,
  firstName: Schema.optional(Schema.String),
  lastName: Schema.optional(Schema.String),
  emailVerified: Schema.Boolean,
  profilePictureUrl: Schema.optional(Schema.URL),
  metadata: Schema.optional(Schema.Record({ key: Schema.String, value: Schema.String })),
  externalId: Schema.optional(Schema.String),
  lastLogInAt: Schema.optional(Schema.DateTimeUtcFromDate),
  createdAt: Schema.DateTimeUtcFromDate,
  updatedAt: Schema.DateTimeUtcFromDate,
}).pipe(
  Schema.brand('User')
)

export type User = typeof User.Type

export class UserModel extends Model.Class<UserModel>('UserModel')({
  ...User.fields,
  id: Model.GeneratedByApp(UserId),
  lastLogInAt: Model.DateTimeFromDate,
  createdAt: Model.DateTimeInsertFromDate,
  updatedAt: Model.DateTimeUpdateFromDate
}) {}
Was this page helpful?