|
- import getFormValues from '@theoryofnekomata/formxtra'
- import {FormEvent} from 'react'
- import {createFetchClient, FetchClient} from '../../utils/api/fetch'
- import * as endpoints from './endpoints'
-
- export default class RingtoneClient {
- private readonly fetchClient: FetchClient
-
- constructor(private readonly baseUrl, private readonly session?) {
- const headers = {}
-
- if (session) {
- headers['Authorization'] = `${session.token_type} ${session.idToken}`
- }
-
- this.fetchClient = createFetchClient({
- baseUrl,
- headers,
- })
- }
-
- save = ({ router, }) => async (e: FormEvent & { submitter: HTMLInputElement | HTMLButtonElement }) => {
- e.preventDefault()
- const form = e.target as HTMLFormElement
- const {tempo, name, data, composerUserSub, id} = getFormValues(form, { submitter: e.submitter })
- const values = {
- composerUserSub,
- name,
- data,
- tempo: Number(tempo),
- }
- const endpoint = id ? endpoints.update(id) : endpoints.create
- const response = await this.fetchClient(endpoint(values))
- if (response.ok) {
- const newValues = await response.json()
- const { id: newId } = newValues.data
- router.replace({
- pathname: '/my/create/ringtones/[id]',
- query: {
- id: newId,
- },
- shallow: true,
- })
- }
- alert(response.statusText)
- }
-
- load = async ({ id }) => {
- const response = await this.fetchClient(endpoints.get(id))
- if (response.ok) {
- const { data } = await response.json()
- return data
- }
- }
- }
|