Skip to content

feat!: v1 #1

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

Merged
merged 19 commits into from
May 16, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ jobs:
runs-on: ubuntu-latest
strategy:
matrix:
node: [14.x, 16.x, 17.x]
node: [16.x, 18.x]
name: Node ${{ matrix.node }}
steps:
- uses: actions/checkout@v1
Expand Down
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -102,3 +102,6 @@ dist

# TernJS port file
.tern-port

# Not necessary for libs
package-lock.json
162 changes: 162 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -1 +1,163 @@
'use strict'
const fp = require('fastify-plugin')

const { Errors } = require('./lib/index')

module.exports = fp(
function fastifyRacePlugin (fastify, globalOpts, next) {
const controllers = new WeakMap()
let error

if (globalOpts != null && typeof globalOpts !== 'object') {
return next(new Errors.BAD_PARAMS('object', typeof globalOpts))
}

globalOpts = Object.assign(
{},
{ handleOnError: true, onRequestClosed: null },
globalOpts
)

if (typeof globalOpts.handleOnError !== 'boolean') {
error = new Errors.BAD_PARAMS('boolean', typeof globalOpts.handleOnError)
} else if (
globalOpts.onRequestClosed != null &&
typeof globalOpts.onRequestClosed !== 'function'
) {
error = new Errors.BAD_PARAMS(
'function',
typeof globalOpts.onRequestClosed
)
}

fastify.decorateRequest('race', race)
fastify.addHook('onResponse', fastifyRacingCleaner)

return next(error)

function fastifyRacingCleaner (request, _reply, done) {
if (controllers.has(request)) {
const { controller, cbs } = controllers.get(request)

if (controller.signal.aborted === false) {
for (const cb of cbs) {
controller.signal.removeEventListener('abort', cb, {
once: true
})
}
}

controllers.delete(request)
}

done()
}

function race (opts = globalOpts) {
const { raw, id: reqId } = this
const handleError = typeof opts === 'function' ? true : opts.handleOnError
const cb = typeof opts === 'function' ? opts : opts.onRequestClosed

if (controllers.has(this)) {
const { controller: ctrl, cbs } = controllers.get(this)

if (ctrl.signal.aborted === true) {
throw new Errors.ALREADY_ABORTED(reqId)
}

if (raw.socket.destroyed === true) {
throw new Errors.SOCKET_CLOSED(reqId)
}

if (cb != null) {
ctrl.signal.addEventListener('abort', cb, {
once: true
})

controllers.set(this, { controller: ctrl, cbs: cbs.concat(cb) })
}

return ctrl.signal
} else {
// eslint-disable-next-line no-undef
const controller = new AbortController()

if (cb != null) {
controller.signal.addEventListener('abort', cb, {
once: true
})
}

if (cb == null) controller.signal.then = theneable.bind(this)

if (raw.socket.destroyed) {
throw new Errors.SOCKET_CLOSED(reqId)
} else {
raw.once(
'close',
function () {
if (controllers.has(this)) {
const { controller: ctrl } = controllers.get(this)
if (ctrl.signal.aborted === false) controller.abort()
}
}.bind(this)
)

if (handleError === true || cb != null) {
raw.once(
'error',
function (err) {
if (controllers.has(this)) {
const { controller: ctrl } = controllers.get(this)
if (ctrl.signal.aborted === false) controller.abort(err)
}
}.bind(this)
)
}
}

controllers.set(this, { controller, cbs: cb != null ? [cb] : [] })

return controller.signal
}

function theneable (resolve, reject) {
const { controller, cbs } = controllers.get(this)

if (raw.socket.destroyed === true) {
return reject(Errors.SOCKET_CLOSED(this.id))
}

if (controller.signal.aborted === true) {
return reject(Errors.ALREADY_ABORTED(this.id))
}

try {
controller.signal.addEventListener('abort', theneableHandler, {
once: true
})

controllers.set(this, {
controller,
cbs: cbs.concat(theneableHandler)
})
} catch (err) {
reject(err)
}

function theneableHandler (evt) {
const event = {
type: evt.type,
reason: controller.signal?.reason
}

resolve(event)
}
}
}
},
{
fastify: '>=3.24.1',
name: 'fastify-racing'
}
)
18 changes: 18 additions & 0 deletions lib/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
const Errors = require('@fastify/error')

module.exports = {
Errors: {
BAD_PARAMS: Errors(
'FST_PLUGIN_RACE_BAD_PARAM',
'Invalid param, expected %s but received %s'
),
ALREADY_ABORTED: Errors(
'FST_PLUGIN_RACE_ALREADY_ABORTED',
"Request with ID '%s' already aborted"
),
SOCKET_CLOSED: Errors(
'FST_PLUGIN_RACE_SOCKET_CLOSED',
"Socket for request with ID '%s' already closed"
)
}
}
22 changes: 15 additions & 7 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "<lib_name>",
"name": "fastify-racing",
"version": "0.0.0",
"description": "<description>",
"description": "Cancel any running operation at the right time on your request handler",
"main": "index.js",
"types": "index.d.ts",
"scripts": {
Expand All @@ -13,27 +13,35 @@
"lint:ci": "standard",
"typescript": "tsd"
},
"engines": {
"node": ">=16.0.0"
},
"keywords": [],
"repository": {
"type": "git",
"url": "git+https://github.com/metcoder95/<lib_name>.git"
"url": "git+https://github.com/metcoder95/fastify-racing.git"
},
"readme": "https://github.com/metcoder95/<lib_name>/blob/main/README.md",
"readme": "https://github.com/metcoder95/fastify-racing/blob/main/README.md",
"bugs": {
"url": "https://github.com/metcoder95/<lib_name>/issues"
"url": "https://github.com/metcoder95/fastify-racing/issues"
},
"author": "metcoder95 <[email protected]>",
"license": "MIT",
"devDependencies": {
"@types/node": "^14.17.6",
"@types/node": "^14.18.13",
"fastify": "^3.28.0",
"husky": "^7.0.2",
"nodemon": "^2.0.15",
"snazzy": "^9.0.0",
"standard": "^16.0.3",
"tap": "^15.0.10",
"tsd": "^0.17.0",
"typescript": "^4.4"
"typescript": "^4.4",
"undici": "^5.0.0"
},
"dependencies": {
"@fastify/error": "^2.0.0",
"fastify-plugin": "^3.0.1"
},
"tsd": {
"directory": "test"
Expand Down
26 changes: 26 additions & 0 deletions test/index.test-d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/// <reference types="node" />
import { FastifyPluginCallback } from 'fastify';
import { FastifyError } from '@fastify/error';


interface AbortEvent {
type: 'abort' | string;
reason?: FastifyError | Error
}

interface FastifyRacing {
handleError?: boolean;
onRequestClosed?: (evt: AbortEvent) => void;
}

declare module 'fastify' {
interface FastifyInstance {
race(cb: FastifyRacing['onRequestClosed']): void
race(opts: FastifyRacing): Promise<AbortEvent>
race(): Promise<AbortEvent>
}
}

declare const FastifyRacing: FastifyPluginCallback<FastifyRacing>;

export default FastifyRacing;
Loading