Skip to content

Instantly share code, notes, and snippets.

@Lcfvs
Created June 17, 2021 00:59
Show Gist options
  • Save Lcfvs/f0a612deadc9dbfd57d7a24db3a4fbcd to your computer and use it in GitHub Desktop.
Save Lcfvs/f0a612deadc9dbfd57d7a24db3a4fbcd to your computer and use it in GitHub Desktop.
typed fetcher
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)
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))
}
}
)
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