Skip to content

Commit

Permalink
Create createTemplate api call
Browse files Browse the repository at this point in the history
This commit changes the structure for the apiClient dependecy injection,
it exports a makeCreateTemplate function that receives the apiClient as
prop and return the createTemplate function, I made this change because
I think this pattern is easier to follow through the application. Also I
intend to change the other api calls in future pr's.
  • Loading branch information
negreirosleo committed Dec 29, 2023
1 parent 7d89f98 commit b12c145
Showing 1 changed file with 34 additions and 0 deletions.
34 changes: 34 additions & 0 deletions frontend/src/infra/template/createTemplate.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { Template, TemplateIntent } from '@/domain/Template'
import { ApiClient } from '../lib/apiClient'
import { BaseError } from '@/_lib/errors/BaseError'

const createTemplateError = (message = 'Failed to create template') => {
const name = 'CreateTemplateError'

return new BaseError({ message, name, code: name })
}

export const makeCreateTemplate = (apiClient: ApiClient) => async (template: TemplateIntent) => {
const validation = TemplateIntent.safeParse(template)

if (!validation.success) {
throw createTemplateError(
validation.error.issues.reduce((acc, nextValue) => `${acc} ${nextValue.message}`, '')
)
}

try {
const response = await apiClient('/v1/timelog/templates', {
method: 'POST',
body: JSON.stringify(template)
})

if (!response.ok) {
throw createTemplateError()
}

return { data: (await response.json()) as Template }
} catch (e) {
throw createTemplateError()
}
}

0 comments on commit b12c145

Please sign in to comment.