Skip to content

Commit

Permalink
Add validators to addAbortListener and AbortSignalAny
Browse files Browse the repository at this point in the history
Signed-off-by: Matteo Collina <hello@matteocollina.com>
  • Loading branch information
mcollina committed Dec 18, 2023
1 parent 0cb37bb commit d83e1e6
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 5 deletions.
15 changes: 12 additions & 3 deletions lib/ours/util.js
Expand Up @@ -18,6 +18,15 @@ const isBlob =
}
/* eslint-enable indent */

const validateAbortSignal = (signal, name) => {
if (signal !== undefined && (signal === null || typeof signal !== 'object' || !('aborted' in signal))) {
throw new ERR_INVALID_ARG_TYPE(name, 'AbortSignal', signal)
}
}
const validateFunction = (value, name) => {
if (typeof value !== 'function') throw new ERR_INVALID_ARG_TYPE(name, 'Function', value)
}

// This is a simplified version of AggregateError
class AggregateError extends Error {
constructor(errors) {
Expand Down Expand Up @@ -136,9 +145,8 @@ module.exports = {
if (signal === undefined) {
throw new ERR_INVALID_ARG_TYPE('signal', 'AbortSignal', signal)
}
// validateAbortSignal(signal, 'signal');
// validateFunction(listener, 'listener');

validateAbortSignal(signal, 'signal')
validateFunction(listener, 'listener')
let removeEventListener
if (signal.aborted) {
queueMicrotask(() => listener())
Expand Down Expand Up @@ -172,6 +180,7 @@ module.exports = {
const ac = new AbortController()
const abort = () => ac.abort()
signals.forEach((signal) => {
validateAbortSignal(signal, 'signals')
signal.addEventListener('abort', abort, {
once: true
})
Expand Down
18 changes: 16 additions & 2 deletions src/util.js
Expand Up @@ -19,6 +19,19 @@ const isBlob =
}
/* eslint-enable indent */

const validateAbortSignal = (signal, name) => {
if (signal !== undefined &&
(signal === null ||
typeof signal !== 'object' ||
!('aborted' in signal))) {
throw new ERR_INVALID_ARG_TYPE(name, 'AbortSignal', signal);
}
};
const validateFunction = (value, name) => {
if (typeof value !== 'function')
throw new ERR_INVALID_ARG_TYPE(name, 'Function', value);
};

// This is a simplified version of AggregateError
class AggregateError extends Error {
constructor(errors) {
Expand Down Expand Up @@ -144,8 +157,8 @@ module.exports = {
if (signal === undefined) {
throw new ERR_INVALID_ARG_TYPE('signal', 'AbortSignal', signal);
}
// validateAbortSignal(signal, 'signal');
// validateFunction(listener, 'listener');
validateAbortSignal(signal, 'signal');
validateFunction(listener, 'listener');

let removeEventListener;
if (signal.aborted) {
Expand All @@ -171,6 +184,7 @@ module.exports = {
const ac = new AbortController()
const abort = () => ac.abort()
signals.forEach(signal => {
validateAbortSignal(signal, 'signals')
signal.addEventListener('abort', abort, { once: true })
})
ac.signal.addEventListener('abort', () => {
Expand Down

0 comments on commit d83e1e6

Please sign in to comment.