Created
June 17, 2021 00:59
-
-
Save Lcfvs/f0a612deadc9dbfd57d7a24db3a4fbcd to your computer and use it in GitHub Desktop.
typed fetcher
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as fetcher from './text-fetcher.js' | |
const fetchText = event => fetcher.resolver.resolve(event) | |
document.querySelector('form') | |
.addEventListener('submit', fetchText) | |
document.querySelector('a') | |
.addEventListener('click', fetchText) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { fulfills, iterable, model } from '@etchedjs/etched' | |
import type, * as types from '@etchedjs/type' | |
const empties = ['GET', 'HEAD'] | |
const reducer = async (promise, action) => | |
action(await promise) | |
const reduce = async (initialValue, actions) => | |
actions.reduce(reducer, initialValue) | |
export const actions = model(iterable) | |
export const json = response => response.json() | |
export const text = response => response.text() | |
export const resolver = model( | |
type('actions', types.etches(actions), e => e()), | |
{ | |
async resolve (event) { | |
event.preventDefault() | |
if (!fulfills(fetcher, this)) { | |
throw new TypeError('Must be fulfilled') | |
} | |
const { actions } = this | |
const { target } = event | |
const { action, href, method = 'GET' } = target | |
return reduce(new Request(action ?? href, { | |
method, | |
...!empties.includes(method.toUpperCase()) && { | |
body: new FormData(form) | |
} | |
}), Object.values(actions)) | |
} | |
} | |
) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { model } from '@etchedjs/etched' | |
import * as fetcher from './fetcher.js' | |
export const actions = model(actions, [ | |
fetch, | |
fetcher.text, | |
data => console.log({ data }) | |
]) | |
export const resolver = model(fetcher.resolver, { | |
actions | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment