Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

177 designs to polymorphic model 3 #182

Merged
merged 7 commits into from
Jun 17, 2024
Merged
Show file tree
Hide file tree
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
40 changes: 39 additions & 1 deletion app/models/design/design.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,34 @@ import {
type IDesignAttributesFill,
type IDesignFill,
} from './fill/fill.server'
import {
type IDesignLayout,
type IDesignAttributesLayout,
} from './layout/layout.server'
import {
type IDesignAttributesLine,
type IDesignLine,
} from './line/line.server'
import {
type IDesignAttributesPalette,
type IDesignPalette,
} from './palette/palette.server'
import {
type IDesignAttributesRotate,
type IDesignRotate,
} from './rotate/rotate.server'
import {
type IDesignAttributesSize,
type IDesignSize,
} from './size/size.server'
import {
type IDesignStroke,
type IDesignAttributesStroke,
} from './stroke/stroke.server'
import {
type IDesignAttributesTemplate,
type IDesignTemplate,
} from './template/template.server'

// Omitting 'createdAt' and 'updatedAt' from the Design interface
// prisma query returns a string for these fields
Expand All @@ -51,7 +75,15 @@ export interface IDesign extends BaseDesign {
// when adding attributes to a design type,
// make sure it starts as optional or is set to a default value
// for when parsing the design from the deserializer
export type IDesignAttributes = IDesignAttributesFill | IDesignAttributesStroke
export type IDesignAttributes =
| IDesignAttributesFill
| IDesignAttributesLayout
| IDesignAttributesLine
| IDesignAttributesPalette
| IDesignAttributesRotate
| IDesignAttributesSize
| IDesignAttributesStroke
| IDesignAttributesTemplate

export interface IDesignParsed extends BaseDesign {
type: designTypeEnum
Expand All @@ -64,7 +96,13 @@ export interface IDesignParsed extends BaseDesign {
// TODO: replace with this ^^
export type IDesignByType = {
designFills: IDesignFill[]
designLayouts: IDesignLayout[]
designLines: IDesignLine[]
designPalettes: IDesignPalette[]
designRotates: IDesignRotate[]
designSizes: IDesignSize[]
designStroke: IDesignStroke[]
designTemplates: IDesignTemplate[]
}

// export interface IDesignsByTypeWithType {
Expand Down
13 changes: 13 additions & 0 deletions app/models/design/layout/layout.delete.server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { prisma } from '#app/utils/db.server'
import { type IDesignLayout } from './layout.server'

export interface IDesignLayoutDeletedResponse {
success: boolean
message?: string
}

export const deleteDesignLayout = ({ id }: { id: IDesignLayout['id'] }) => {
return prisma.design.delete({
where: { id },
})
}
52 changes: 52 additions & 0 deletions app/models/design/layout/layout.get.server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import { invariant } from '@epic-web/invariant'
import { z } from 'zod'
import { DesignTypeEnum } from '#app/schema/design'
import { prisma } from '#app/utils/db.server'
import { deserializeDesign } from '../utils'
import { type IDesignLayout } from './layout.server'

export type queryWhereArgsType = z.infer<typeof whereArgs>
const whereArgs = z.object({
id: z.string().optional(),
ownerId: z.string().optional(),
artworkVersionId: z.string().optional(),
layerId: z.string().optional(),
})

// TODO: Add schemas for each type of query and parse with zod
// aka if by id that should be present, if by slug that should be present
// owner id should be present unless admin (not set up yet)
const validateQueryWhereArgsPresent = (where: queryWhereArgsType) => {
const nullValuesAllowed: string[] = []
const missingValues: Record<string, any> = {}
for (const [key, value] of Object.entries(where)) {
const valueIsNull = value === null || value === undefined
const nullValueAllowed = nullValuesAllowed.includes(key)
if (valueIsNull && !nullValueAllowed) {
missingValues[key] = value
}
}

if (Object.keys(missingValues).length > 0) {
console.log('Missing values:', missingValues)
throw new Error(
'Null or undefined values are not allowed in query parameters for design layout.',
)
}
}

export const getDesignLayout = async ({
where,
}: {
where: queryWhereArgsType
}): Promise<IDesignLayout | null> => {
validateQueryWhereArgsPresent(where)
const design = await prisma.design.findFirst({
where: {
...where,
type: DesignTypeEnum.LAYOUT,
},
})
invariant(design, 'Design Layout Not found')
return deserializeDesign({ design }) as IDesignLayout
}
23 changes: 23 additions & 0 deletions app/models/design/layout/layout.server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { type DesignTypeEnum } from '#app/schema/design'
import { type IDesignSubmission, type IDesignParsed } from '../design.server'

export interface IDesignLayout extends IDesignParsed {
type: typeof DesignTypeEnum.LAYOUT
attributes: IDesignAttributesLayout
}

export type IDesignLayoutStyle = 'random' | 'grid'

// when adding attributes to an design type,
// make sure it starts as optional or is set to a default value
// for when parsing the design from the deserializer
export interface IDesignAttributesLayout {
basis?: IDesignLayoutStyle
count?: number
rows?: number
columns?: number
}

export interface IDesignLayoutSubmission
extends IDesignSubmission,
IDesignAttributesLayout {}
20 changes: 20 additions & 0 deletions app/models/design/layout/layout.update.server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { type IDesign, type IDesignUpdateData } from '../design.server'
import {
type IDesignLayoutSubmission,
type IDesignAttributesLayout,
type IDesignLayout,
} from './layout.server'

export interface IDesignLayoutUpdatedResponse {
success: boolean
message?: string
updatedDesignLayout?: IDesign
}

export interface IDesignLayoutUpdateSubmission extends IDesignLayoutSubmission {
id: IDesignLayout['id']
}

export interface IDesignLayoutUpdateData extends IDesignUpdateData {
attributes: IDesignAttributesLayout
}
53 changes: 53 additions & 0 deletions app/models/design/layout/layout.update.style.server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import { type IntentActionArgs } from '#app/definitions/intent-action-args'
import { type IUser } from '#app/models/user/user.server'
import { EditDesignLayoutStyleSchema } from '#app/schema/design/layout'
import { ValidateDesignSubmissionStrategy } from '#app/strategies/validate-submission.strategy'
import { validateEntitySubmission } from '#app/utils/conform-utils'
import { prisma } from '#app/utils/db.server'
import {
type IDesignLayoutStyle,
type IDesignAttributesLayout,
type IDesignLayout,
} from './layout.server'
import { stringifyDesignLayoutAttributes } from './utils'

export const validateEditStyleDesignLayoutSubmission = async ({
userId,
formData,
}: IntentActionArgs) => {
const strategy = new ValidateDesignSubmissionStrategy()

return await validateEntitySubmission({
userId,
formData,
schema: EditDesignLayoutStyleSchema,
strategy,
})
}

export interface IDesignLayoutUpdateStyleSubmission {
userId: IUser['id']
id: IDesignLayout['id']
style: IDesignLayoutStyle
}

interface IDesignLayoutUpdateStyleData {
attributes: IDesignAttributesLayout
}

export const updateDesignLayoutStyle = ({
id,
data,
}: {
id: IDesignLayout['id']
data: IDesignLayoutUpdateStyleData
}) => {
const { attributes } = data
const jsonAttributes = stringifyDesignLayoutAttributes(attributes)
return prisma.design.update({
where: { id },
data: {
attributes: jsonAttributes,
},
})
}
39 changes: 39 additions & 0 deletions app/models/design/layout/utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { ZodError } from 'zod'
import { DesignAttributesLayoutSchema } from '#app/schema/design/layout'
import { type IDesignAttributesLayout } from './layout.server'

export const parseDesignLayoutAttributes = (
attributes: string,
): IDesignAttributesLayout => {
try {
return DesignAttributesLayoutSchema.parse(JSON.parse(attributes))
} catch (error: any) {
if (error instanceof ZodError) {
throw new Error(
`Validation failed for asset image: ${error.errors.map(e => e.message).join(', ')}`,
)
} else {
throw new Error(
`Unexpected error during validation for asset image: ${error.message}`,
)
}
}
}

export const stringifyDesignLayoutAttributes = (
attributes: IDesignAttributesLayout,
): string => {
try {
return JSON.stringify(DesignAttributesLayoutSchema.parse(attributes))
} catch (error: any) {
if (error instanceof ZodError) {
throw new Error(
`Validation failed for asset image: ${error.errors.map(e => e.message).join(', ')}`,
)
} else {
throw new Error(
`Unexpected error during validation for asset image: ${error.message}`,
)
}
}
}
13 changes: 13 additions & 0 deletions app/models/design/line/line.delete.server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { prisma } from '#app/utils/db.server'
import { type IDesignLine } from './line.server'

export interface IDesignLineDeletedResponse {
success: boolean
message?: string
}

export const deleteDesignLine = ({ id }: { id: IDesignLine['id'] }) => {
return prisma.design.delete({
where: { id },
})
}
52 changes: 52 additions & 0 deletions app/models/design/line/line.get.server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import { invariant } from '@epic-web/invariant'
import { z } from 'zod'
import { DesignTypeEnum } from '#app/schema/design'
import { prisma } from '#app/utils/db.server'
import { deserializeDesign } from '../utils'
import { type IDesignLine } from './line.server'

export type queryWhereArgsType = z.infer<typeof whereArgs>
const whereArgs = z.object({
id: z.string().optional(),
ownerId: z.string().optional(),
artworkVersionId: z.string().optional(),
layerId: z.string().optional(),
})

// TODO: Add schemas for each type of query and parse with zod
// aka if by id that should be present, if by slug that should be present
// owner id should be present unless admin (not set up yet)
const validateQueryWhereArgsPresent = (where: queryWhereArgsType) => {
const nullValuesAllowed: string[] = []
const missingValues: Record<string, any> = {}
for (const [key, value] of Object.entries(where)) {
const valueIsNull = value === null || value === undefined
const nullValueAllowed = nullValuesAllowed.includes(key)
if (valueIsNull && !nullValueAllowed) {
missingValues[key] = value
}
}

if (Object.keys(missingValues).length > 0) {
console.log('Missing values:', missingValues)
throw new Error(
'Null or undefined values are not allowed in query parameters for design line.',
)
}
}

export const getDesignLine = async ({
where,
}: {
where: queryWhereArgsType
}): Promise<IDesignLine | null> => {
validateQueryWhereArgsPresent(where)
const design = await prisma.design.findFirst({
where: {
...where,
type: DesignTypeEnum.LINE,
},
})
invariant(design, 'Design Line Not found')
return deserializeDesign({ design }) as IDesignLine
}
29 changes: 29 additions & 0 deletions app/models/design/line/line.server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { type DesignTypeEnum } from '#app/schema/design'
import { type IDesignSubmission, type IDesignParsed } from '../design.server'

export interface IDesignLine extends IDesignParsed {
type: typeof DesignTypeEnum.LINE
attributes: IDesignAttributesLine
}

export type IDesignLineBasis =
| 'size'
| 'width'
| 'height'
| 'canvas-width'
| 'canvas-height'

export type IDesignLineFormat = 'pixel' | 'percent'

// when adding attributes to an design type,
// make sure it starts as optional or is set to a default value
// for when parsing the design from the deserializer
export interface IDesignAttributesLine {
basis?: IDesignLineBasis
format?: IDesignLineFormat
width?: number
}

export interface IDesignLineSubmission
extends IDesignSubmission,
IDesignAttributesLine {}
Loading
Loading