-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathlesson6-validation.ts
181 lines (152 loc) · 4.42 KB
/
lesson6-validation.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
import * as t from 'io-ts'
import * as TE from 'fp-ts/TaskEither'
import { pipe } from 'fp-ts/function'
import * as E from 'fp-ts/Either'
import * as A from 'fp-ts/Apply'
import axios, { AxiosResponse } from 'axios'
// API TYPES
// These are defined using io-ts
// which is like Joi or Yup but also lets us derive a type
// for the output of the validator...
const breed = t.union([
t.literal('pug'),
t.literal('shiba'),
t.literal('spanish'),
])
// ...like this
type Breed = t.TypeOf<typeof breed>
// post data in our requests
const apiRequest = t.type({
breed,
name: t.string,
age: t.number,
})
type ApiRequest = t.TypeOf<typeof apiRequest>
// response type we will be returning
const apiResponse = t.type({
message: t.string,
url: t.string,
})
type ApiResponse = t.TypeOf<typeof apiResponse>
// validator for data we will be receiving from the external API
const dogApiResponse = t.type({
message: t.string,
status: t.literal('success'),
})
// ERROR TYPE
// all of the different things that can go wrong in our API, defined below:
type ApiError =
| AgeTooLow
| NameIsEmpty
| RequestValidationFailure
| DogApiValidationFailure
| AxiosFetchError
type AgeTooLow = { type: 'AgeTooLow' }
type NameIsEmpty = { type: 'NameIsEmpty' }
type AxiosFetchError = { type: 'AxiosFetchError' }
type DogApiValidationFailure = {
type: 'ApiValidationFailure'
errors: t.Errors
}
type RequestValidationFailure = {
type: 'RequestValidationFailure'
errors: t.Errors
}
// constructor functions for our errors
const ageTooLow = (): AgeTooLow => ({ type: 'AgeTooLow' })
const nameIsEmpty = (): NameIsEmpty => ({ type: 'NameIsEmpty' })
const axiosFetchError = (): AxiosFetchError => ({
type: 'AxiosFetchError',
})
const dogApiValidationFailure = (
errors: t.Errors
): DogApiValidationFailure => ({
type: 'ApiValidationFailure',
errors,
})
const requestValidationFailure = (
errors: t.Errors
): RequestValidationFailure => ({
type: 'RequestValidationFailure',
errors,
})
// COMBINATORS
// These functions will be helpful in making our API more resilient
// retry a given task `te` X times on failure
const withRetries = <E, A>(
te: TE.TaskEither<E, A>,
retries: number
): TE.TaskEither<E, A> =>
pipe(
te,
TE.orElse(err =>
retries > 0 ? withRetries(te, retries - 1) : TE.left(err)
)
)
// validate input using the provided io-ts `validator`
const withIoTs = <E, A>(
validator: t.Type<A>,
toError: (e: t.Errors) => E
) => (postData: unknown): TE.TaskEither<E, A> =>
TE.fromEither(
pipe(
validator.decode(postData),
E.orElse(err => E.left(toError(err)))
)
)
// used to simulate failure
// `probability` is between 0 and 1 that task fails
// `te` is a TaskEither that you wish to fail sometimes
// `err` is the error you wish it to fail with
export const sometimesExplode = <E, A>(
probability: number,
te: TE.TaskEither<E, A>,
err: E
): TE.TaskEither<E, A> => {
const rand = Math.random()
return rand < probability ? TE.left(err) : te
}
// FUNCTIONS
// get url for Dog fetch
const getBreedUrl = (breed: Breed): string =>
`https://dog.ceo/api/breed/${breed}/images/random`
// Axios.get wrapped in a TaskEither
const axiosGet = (
url: string
): TE.TaskEither<AxiosFetchError, AxiosResponse<unknown>> =>
TE.tryCatch(
() => axios.get(url),
_ => axiosFetchError()
)
// fetch dog from API (retrying 5 times)
// unwrap AxiosResponse
// validate response using io-ts
// return `message` from the payload
export const getDogWithValidation = (
breed: Breed
): TE.TaskEither<ApiError, string> => undefined as any
// if the name and age are valid, then construct a nice birthday message
const makeBirthdayMessage = (
req: ApiRequest
): E.Either<AgeTooLow | NameIsEmpty, string> => {
if (req.age < 1) {
return E.left(ageTooLow())
}
if (req.name.length < 1) {
return E.left(nameIsEmpty())
}
const message = `Happy Birthday ${req.name}, ${req.age} years old today!`
return E.right(message)
}
// pass multiple TaskEithers to run them in parallel and return
// a tuple of results
const parallel = A.sequenceT(TE.taskEither)
// the whole endpoint should do the following
// validate the input with the `apiRequest` validator
// take the output and then...
// a) fetch a dog with `getDogWithValidation`
// b) try to make a birthday message
// then combine those to create an `apiResponse`
export const endpoint = (
postData: unknown
): TE.TaskEither<ApiError, ApiResponse> => undefined as any