jhermsmeier / node-http-link-header

Parse & format HTTP link headers according to RFC 8288
MIT License
39 stars 12 forks source link

Implement a class `Link` method `setUnique` #28

Closed jaydenseric closed 2 years ago

jaydenseric commented 2 years ago

This PR implements a class Link method setUnique that sets a reference if a reference with similar properties isn’t already set. This is very useful for avoiding adding redundant duplicate refs to a link, for example when using rel='preload'.

In every project I have used this package as a dependency I have had to create and use this utility function:

/**
 * Sets a `Link` header link, skipping the operation if the same URI and `rel`
 * combination has already been set. It’s assumed that other attributes such as
 * `as` or `type` won’t vary for a given URI and `rel` combination.
 * @see [`http-link-header` on npm](https://npm.im/http-link-header).
 * @param {import("http-link-header")} linkHeader `LinkHeader` instance.
 * @param {import("http-link-header").Reference} ref Link config.
 */
export const linkHeaderSetUnique = (linkHeader, ref) => {
  if (
    !linkHeader.refs.some(({ uri, rel }) => rel === ref.rel && uri === ref.uri)
  )
    linkHeader.set(ref);
};

This PR goes a little further than that utility function with the setUnique method as it shallow compares all reference properties, not just uri and rel.

jhermsmeier commented 2 years ago

Thank you! Published in http-link-header@1.1.0