jhermsmeier / node-http-link-header

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

Link.has(attr, value) always returns true #14

Closed greengiraffe closed 5 years ago

greengiraffe commented 5 years ago

Problem

Link.has('someattr', 'somevalue') always returns true, even if 'someattr' and 'somevalue' are not present in link header.

Technical description

This is what Link.has(attr, value) (Line #101) looks like:

has( attr, value ) {
  return this.get( attr, value ) != null
}

It checks if Link.get(attr, value) returned null.

Link.get(attr, value) (Line #83) always returns an Array, never null. In case the provided attr/value pair is not present, an empty array is returned. An empty array is truthy and not null, thus Link.has always returns true.

Solution

Either change Link.has to check for this.get( attr, value ).length or update Link.get to return null when the array is empty. I tend to prefer the latter, because then the returned value is falsy.

jhermsmeier commented 5 years ago

Thanks! Fix published in http-link-header@1.0.1

dhui commented 5 years ago

Checking the length of the array seems like a cleaner solution to me. That way, the return type for get() is always an Array.

We could also speed up has() in the friendly case. e.g. has() has it's own implementation and breaking out of the search if an attr with the given value is found. It'd save a bit of memory as well.

jhermsmeier commented 5 years ago

@dhui feel free to send a PR :)