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

Implement a class Link method setUnique #28

Conversation

jaydenseric
Copy link
Contributor

@jaydenseric jaydenseric commented Nov 8, 2022

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.

@jaydenseric jaydenseric marked this pull request as ready for review November 8, 2022 07:00
@jhermsmeier jhermsmeier merged commit 8ea349d into jhermsmeier:master Nov 13, 2022
@jhermsmeier
Copy link
Owner

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

@jaydenseric jaydenseric deleted the jaydenseric/implement-class-Link-method-setUnique branch November 13, 2022 20:45
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

Successfully merging this pull request may close these issues.

None yet

2 participants