
-- 단순 요청 조건을 벗어나면 브라우저가 본 요청 전에 OPTIONS 를 보낸다
send :: [Method] -> Request -> Either Blocked Response
send allowed req
| simple req = Right (fetch req)
| OPTIONS `elem` allowed = Right (fetch req) -- preflight 통과 후 본 요청
| otherwise = Left PreflightFailed
cloudFrontDefault = [GET, HEAD] -- 캐시 동작에 OPTIONS 를 허용해야 한다

-- 파일 업로드: FormData 에 담아 body 로
formData :: File -> [File] -> FormData
formData single multiple =
("single", single) : [("multiple_" ++ show i, f) | (i, f) <- zip [0 ..] multiple]
-- fetch(url, { method: 'POST', body: formData })

-- 이미지 다운로드: 응답을 Buffer 로 받아 파일로
download :: Url -> IO ()
download url = do
buf <- fromArrayBuffer <$> (fetch url >>= arrayBuffer)
createDirectoryIfMissing folder -- 없으면 mkdir
writeFile (folder </> takeFileName (pathname url)) buf

-- mock: 요청이 나가는 곳에서 가로챈다
intercept :: Origin -> Interceptor
intercept Browser = ServiceWorker -- addEventListener('fetch', e => e.respondWith(mock(e.request))) — MSW 의 원리
intercept Server = NodeHook -- getServerSideProps 처럼 서버에서 나가는 요청 — nock
-- 원리는 간단하지만 이미 잘 만든 라이브러리가 있다 — 아이디어로만