Skip to content

Commit

Permalink
Init Repo
Browse files Browse the repository at this point in the history
  • Loading branch information
salwador committed Oct 19, 2024
0 parents commit d9d18fc
Show file tree
Hide file tree
Showing 16 changed files with 616 additions and 0 deletions.
45 changes: 45 additions & 0 deletions .github/workflows/build_n_test.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
name: "Build & Test"

on:
push:
branches: [main]
pull_request:
branches: ['*']
workflow_dispatch:

jobs:
start:
name: Build & Test (Node.JS v${{ matrix.node }}, Fastify v${{ matrix.fastify }})
runs-on: ubuntu-latest

strategy:
fail-fast: false
matrix:
node: [ 22, 21, 20, 19 ]
fastify: ['4.14.0', '4.14', '4.15', '4.16', '5']

steps:
- name: Basic (1/1) - Checkout Project
uses: actions/checkout@v4

- name: Node.JS (1/3) - Installing
uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node }}

- name: Node.JS (2/3) - NPM Modules Installing
run: |
npm install
- name: Node.JS (3/3) - Specific Fastify Installing
run: |
npm install fastify@${{ matrix.fastify }}
# Устанавливаем и тестируем с Fastify 4.14
- name: Build (1/2) - TypeScript Compilation
run: npm run build

- name: Build (2/2) - Launch Test
run: |
npm run test
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
/node_modules
package-lock.json
5 changes: 5 additions & 0 deletions .npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
/src/**/*.ts
/dist/test/**
/info/**
tsconfig.json
.github
22 changes: 22 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
MIT License

Copyright (c) 2024
https://github.com/bsnext

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
66 changes: 66 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
# Fastify-Bowser
![Build & Test](https://github.com/bsnext/fastify-bowser/actions/workflows/build_n_test.yml/badge.svg)
![Node.JS Supported](https://badgen.net/static/Node.JS/%3E=19.0.0/green)
![Fastify Supported](https://badgen.net/static/Fastify/%3E=14/green)
![Install Size](https://badgen.net/packagephobia/install/@bsnext/fastify-bowser)
![Dependencies](https://badgen.net/bundlephobia/dependency-count/@bsnext/fastify-bowser)
![License](https://badgen.net/static/license/MIT/blue)

The plugin adds the "request.useragent" property, which returns the parsed data.

**Tested on Fastify v4.14+ and Node.JS v19+!**<br>
https://github.com/bsnext/fastify-bowser/actions/workflows/build_n_test.yml

Why "[bowser](https://www.npmjs.com/package/bowser)", not "[ua-parser-js](https://www.npmjs.com/package/ua-parser-js)" or other library?
Bowser it's a zero-dependency package with MIT license, unlike "ua-parser-js" under AGPL-3.0. Both of these libraries are good, but on top of that, bowser [is about x4 times more faster](https://github.com/bsnext/fastify-bowser/blob/master/info/benchmark.md).

Why not [those package](https://github.com/Eomm/fastify-user-agent)? Under hood it have a "[useragent](https://www.npmjs.com/package/useragent)" - library with 2 dependencies. One of that is "LRU-Cache". But without cache it [have a performance less than both previously](https://github.com/bsnext/fastify-bowser/blob/master/info/benchmark.md) mentioned libraries. Also, **this library excludes parsing of user-agent until you call this property in request**.

## Installing:
```bash
npm install @bsnext/fastify-bowser
```

## Usage:
```ts
import FastifyBowser from '@bsnext/fastify-bowser'; // TS
import { default as FastifyBowser } from "@bsnext/fastify-bowser"; // MJS
const { default: FastifyBowser } = require(`@bsnext/fastify-bowser`); // CJS

const server = Fastify();
await server.register(FastifyBowser, {
// Use parsed user-agent cache
cache: boolean = false;

// Cache limit. Will be automatically purged, if cache size reach limit.
cacheLimit: number = 100;

// Automatically cache purge interval in milliseconds.
cachePurgeTime: number = 60 * 5;
});

```

## Example

```ts
import Fastify from 'fastify';
import FastifyBowser from '@bsnext/fastify-bowser';

const server = Fastify(...);
await server.register(FastifyBowser, { cache: true });

server.get(`/test`, function(request, response) {
response.send(request.useragent);

/* {
browser: { name: 'Chrome', version: '129.0.0.0' },
os: { name: 'Windows', version: 'NT 10.0', versionName: '10' },
platform: { type: 'desktop' },
engine: { name: 'Blink' }
} */
})

server.listen({ port: 8080 });

```
29 changes: 29 additions & 0 deletions dist/index.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
declare module "fastify" {
interface FastifyRequest {
useragent: {
ua: string;
browser: {
name: string | undefined;
version: string | undefined;
};
os: {
name: string | undefined;
version: string | undefined;
versionName: string | undefined;
};
platform: {
type: string | undefined;
};
engine: {
name: string | undefined;
};
};
}
}
export interface PluginOptions {
cache?: boolean;
cacheLimit?: number;
cachePurgeTime?: number;
}
declare const _default: (fastify: import("fastify").FastifyInstance<import("fastify").RawServerDefault, import("http").IncomingMessage, import("http").ServerResponse<import("http").IncomingMessage>, import("fastify").FastifyBaseLogger, import("fastify").FastifyTypeProviderDefault>, initOptions: PluginOptions, done: (err?: Error) => void) => void;
export default _default;
63 changes: 63 additions & 0 deletions dist/index.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions dist/index.js.map

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions dist/test/index.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export {};
65 changes: 65 additions & 0 deletions dist/test/index.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions dist/test/index.js.map

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

61 changes: 61 additions & 0 deletions info/benchmark.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
#### If you wanna try that, disable "LRU" in "useragent" for fair benchmark:
```js
// node_modules/useragent/index.js : line 510

exports.lookup = function lookup(userAgent, jsAgent) {
var key = (userAgent || '')+(jsAgent || '');
return exports.parse(userAgent, jsAgent);
};
```

#### Modules:
```
npm install ua-parser-js bowser useragent
```

#### Code:

```ts
import { UAParser } from "ua-parser-js";
import * as Bowser from "bowser";
import * as Useragent from "useragent";

import * as Benchmark from "benchmark";

const bench = new Benchmark.Suite();

/////////////////////////////

const uaParserInstance = new UAParser();

/////////////////////////////

bench.add(`bowser`, function () {
const result = Bowser.parse(`Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36`);
});

bench.add(`ua-parser-js`, function () {
const result = uaParserInstance.setUA(`Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36`).getResult();
});

bench.add(`useragent`, function () {
const result = Useragent.lookup(`Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36`);
});

/////////////////////////////

bench.on('cycle', function (e) {
console.log(e.target.toString());
});

bench.run();
```

#### Results:
```js
bowser x 188,346 ops/sec ±0.48% (93 runs sampled)
ua-parser-js x 50,341 ops/sec ±0.70% (94 runs sampled)
useragent x 34,391 ops/sec ±0.37% (93 runs sampled)

// Node v22.8.0, Win 11, Ryzen 7 3800X 3.89 GHz, 32 GB RAM 3200 MHz
```
Loading

0 comments on commit d9d18fc

Please sign in to comment.