omrilotan / isbot

🤖/👨‍🦰 Detect bots/crawlers/spiders using the user agent string
https://isbot.js.org/
The Unlicense
933 stars 77 forks source link

Add ability to create multiple instances #153

Closed richardscarrott closed 3 years ago

richardscarrott commented 3 years ago

Problem

We have a handful of reasons to change the behaviour of our site based on whether the user is a bot. However, they have subtly different requirements. For example:

import isBot from 'isbot';

export const shouldTrack = (ua) => !isBot(ua);
export const shouldFlushHeadEarly = (ua) => !isBot(ua); // exclude chrome-lighthouse and webpagetest
export const shouldDetectRegion = (ua) => !isBot(ua); // include foo and bar
// etc.

Possible solution

Would it make sense to expose a constructor (or factory fn) which had its own pattern state?

import { createIsBot } from 'isbot';

export const shouldTrack = createIsBot();
export const shouldFlushHeadEarly = createIsBot({
  exclude: ['chrome-lighthouse', 'PTST/4']
});
export const shouldDetectRegion = createIsBot({
  include: ['foo', 'bar']
});
// etc.
omrilotan commented 3 years ago

That's an interesting case. While the emphasis of this repo is usually on maintaining a performant and comprehensive pattern, this is an interesting usage. I'll have a think about this and see if it's worth it to add a bit of complexity to this module.

omrilotan commented 3 years ago

I'm testing a solution at #155 . You can test it, too:

npm i isbot@spawn
omrilotan commented 3 years ago

@richardscarrott would also appreciate your review of the interface, and continue the discussion on #155

Spawn: Create new instances

Create new instances of isbot. Instance is spawned using spawner's list as base

const one = isbot.spawn()
const two = isbot.spawn()
two.exclude(['chrome-lighthouse'])
one('Chrome-Lighthouse') // true
two('Chrome-Lighthouse') // false

Create isbot using custom list (instead of the maintained list)

const lean = isbot.spawn([ 'bot' ])
lean('Googlebot') // true
lean('Chrome-Lighthouse') // false