Skip to content

Commit

Permalink
refactor: attribute transforms
Browse files Browse the repository at this point in the history
  • Loading branch information
juni0r committed Nov 7, 2023
1 parent df9e671 commit fed4d38
Show file tree
Hide file tree
Showing 4 changed files with 19 additions and 24 deletions.
7 changes: 3 additions & 4 deletions src/baseModel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ import {
} from './errors'

import result from 'lodash.result'
import forEach from 'lodash.foreach'
import mapValues from 'lodash.mapvalues'

import type {
Attributes,
Expand All @@ -22,10 +24,8 @@ import type {
Scoped,
ToJSON,
ID,
Transform,
} from './types'
import { Transform } from './transform'
import forEach from 'lodash.foreach'
import mapValues from 'lodash.mapvalues'

export class BaseModel {
static client: SupabaseClient<any, any, any>
Expand Down Expand Up @@ -244,5 +244,4 @@ export class BaseModel {
}
}
}

export default BaseModel
19 changes: 12 additions & 7 deletions src/model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,16 @@ import forEach from 'lodash.foreach'

import { baseModel } from './config'
import { BaseModel } from './baseModel'
import { Transform } from './transform'
import { zodSchemaOf } from './schema'
import { Dict } from './util'
import { Dict, identity } from './util'

import type { Attributes, SchemaOf, Extend, ModelOptions } from './types'
import type {
ModelOptions,
Attributes,
Transform,
SchemaOf,
Extend,
} from './types'

export function defineModel<Attrs extends Attributes>(
attributes: Attrs,
Expand All @@ -25,12 +30,12 @@ export function defineModel<Attrs extends Attributes>(
if (tableName) model.tableName = tableName
if (primaryKey) model.primaryKey = primaryKey

forEach(attributes, ({ column, take, emit }, key) => {
model.transforms[key] = new Transform(
column || model.naming(key),
forEach(attributes, ({ column, take = identity, emit = identity }, key) => {
model.transforms[key] = {
column: column || model.naming(key),
take,
emit,
)
}

Object.defineProperty(model.prototype, key, {
get() {
Expand Down
11 changes: 0 additions & 11 deletions src/transform.ts

This file was deleted.

6 changes: 4 additions & 2 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,8 +79,10 @@ export interface KeyMapper {
(key: string): string
}

export interface TransformFn<In = any, Out = any> {
(val: In): Out
export interface Transform<In = any, Out = any> {
column: string
take: (val: Out) => In
emit: (val: In) => Out
}

export interface Scoped<T = any> {
Expand Down

0 comments on commit fed4d38

Please sign in to comment.