|
| 1 | +import {flow, pipe} from 'fp-ts/lib/function'; |
| 2 | +import * as E from 'fp-ts/Either'; |
| 3 | +import {html, safe, toLoggedInContent} from '../../types/html'; |
| 4 | +import {Form} from '../../types/form'; |
| 5 | +import { DomainEvent } from '../../types'; |
| 6 | +import { renderEvent } from '../../queries/shared-render/render-domain-event'; |
| 7 | +import * as t from 'io-ts'; |
| 8 | +import * as tt from 'io-ts-types'; |
| 9 | +import { formatValidationErrors } from 'io-ts-reporters'; |
| 10 | +import { failureWithStatus } from '../../types/failure-with-status'; |
| 11 | +import { StatusCodes } from 'http-status-codes'; |
| 12 | +import * as O from 'fp-ts/Option'; |
| 13 | + |
| 14 | +type ViewModel = { |
| 15 | + event: O.Option<DomainEvent>, |
| 16 | + event_id: tt.UUID, |
| 17 | +}; |
| 18 | + |
| 19 | +const renderForm = (viewModel: ViewModel) => |
| 20 | + O.isSome(viewModel.event) ? |
| 21 | + pipe( |
| 22 | + html` |
| 23 | + <h1>Exclude an event</h1> |
| 24 | + <p>Are you sure you want to exclude (delete) this event? This form should only be used |
| 25 | + </p> |
| 26 | + ${renderEvent(viewModel.event.value)} |
| 27 | + <form action="/events/exclude-event" method="post"> |
| 28 | + <input type="hidden" name="event_id" value="${viewModel.event_id}"/> |
| 29 | + <button type="submit">Confirm</button> |
| 30 | + </form> |
| 31 | + `, |
| 32 | + toLoggedInContent(safe('Exclude event')) |
| 33 | + ) : pipe( |
| 34 | + html` |
| 35 | + <h1>Unknown event: ${viewModel.event_id}</h1> |
| 36 | + `, |
| 37 | + toLoggedInContent(safe('Exclude event')) |
| 38 | + ); |
| 39 | + |
| 40 | +const paramsCodec = t.strict({ |
| 41 | + event_id: tt.UUID |
| 42 | +}); |
| 43 | + |
| 44 | +const constructForm: Form<ViewModel>['constructForm'] = input => ({events}) => pipe( |
| 45 | + input, |
| 46 | + paramsCodec.decode, |
| 47 | + E.mapLeft( |
| 48 | + flow( |
| 49 | + formatValidationErrors, |
| 50 | + failureWithStatus( |
| 51 | + 'Parameters submitted to the form were invalid', |
| 52 | + StatusCodes.BAD_REQUEST |
| 53 | + ) |
| 54 | + ) |
| 55 | + ), |
| 56 | + E.map(params => params.event_id), |
| 57 | + E.map(event_id => ({event_id, event: O.fromNullable(events.findLast((event) => event.event_id === event_id))})) |
| 58 | +); |
| 59 | + |
| 60 | +export const excludeEventForm: Form<ViewModel> = { |
| 61 | + renderForm, |
| 62 | + constructForm, |
| 63 | +}; |
0 commit comments