Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Is it possible to make abstract interface for this library functionality? #79

Closed
krutoo opened this issue Aug 8, 2023 · 2 comments
Closed

Comments

@krutoo
Copy link

krutoo commented Aug 8, 2023

Hi, i develop some library for fetch function - fetch-tools:
https://github.com/krutoo/fetch-tools

Currently it provides a way to add middleware for fetching process.

Middleware is just a function that receives:

  • Request - request object created from fetch payload
  • Next - function that receives Request and returns Promise<Response>

Middleware should return Response | Promise<Response>

In fetch-tools package there is a simple middleware for collect cookie on the server. But recently I realized that I did not implement it quite correctly.

I see that fetch-cookie makes a lot of work to collect/pass cookie according to spec and browser behavior

Can i create properly worked solution based on fetch-cookie as middleware?

@krutoo
Copy link
Author

krutoo commented Aug 8, 2023

i think it can be look like this:

import { Middleware } from '@krutoo/fetch-tools';

interface CookieStore {
  // ...
}

export function cookieMiddleware(store: CookieStore): Middleware {
  return async (request, next) => {
    const nextHeaders = new Headers(request.headers);

    // here we get cookies from the storage that are needed only for this request
    nextHeaders.append('cookie', store.getCookies(request));

    // copy original request with add cookie
    const nextRequest = new Request(request, { headers: nextHeaders })

    // make fetch
    const response = await next(nextRequest);

    // handle set-cookie headers
    if (response.headers.has('set-cookie')) {
      response.headers.forEach((headerValue, headerName) => {
        if (headerName === 'set-cookie') {
          store.setCookie(headerValue);
        }
      });
    }

    return response;
  };
}

@valeriangalliat
Copy link
Owner

Hey!

Because fetch-cookie takes a fetch instance to call next, it's essentially a middleware :)

You should be able to wrap it like this:

import fetchCookie from 'fetch-cookie'

export function cookieMiddleware(store: CookieStore): Middleware {
  return async (request, next) => {
    return await fetchCookie(next, store)(request)
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants