OP-Engineering / link-preview-js

⛓ Extract web links information: title, description, images, videos, etc. [via OpenGraph], runs on mobiles and node.
MIT License
770 stars 124 forks source link

Pass `signal` as a property #97

Closed CarlosManotas closed 3 years ago

CarlosManotas commented 3 years ago

I'm trying to cancel some requests with the react hook useEffect this could be an example

import { getLinkPreview } from "link-preview-js";
...
useEffect(() => {
 const controller = new AbortController();
 const signal = controller.signal;
 getLinkPreview(url, { headers: { 'user-agent': ... }, timeout: 4000, signal })
...
 // and then cleanup function
 return () => controller.abort()
}, []);

The Main problem could be that because in the base code we have this for the timeout

...
  const timeout = options?.timeout ?? 3000; // 3 second timeout default
  const controller = new AbortController();
  const timeoutCounter = setTimeout(() => controller.abort(), timeout);

  const fetchOptions = {
    headers: options?.headers ?? {},
    redirect: `follow` as `follow`,
    signal: controller.signal,
  };
 ...

Maybe a solution can be something like this, We can have a getter for the controller

  import { getLinkPreview, getController } from "link-preview-js";
  ...
  useEffect(() => {
   const controller = getController();
   getLinkPreview(url, { headers: { 'user-agent': ... }, timeout: 4000 })... 
   return () => controller.abort() //  <---- it's still works  for timeout and  abort
}, []);

Thanks.

ospfranco commented 3 years ago

if you really need this amount of control why not do the request yourself and then just use getPreviewFromContent?

ospfranco commented 3 years ago

Didn't get a response, plus the proposed solution is not so simple since the controller is instanciated per request... On the other hand if you need this amount of control I think it is better to do the request yourself since this is the most trivial part of three library