Skip to content

Commit

Permalink
Refactor ROWS_PER_PAGE codec into a generic one
Browse files Browse the repository at this point in the history
  • Loading branch information
Onitoxan committed Jan 21, 2025
1 parent dfa8d62 commit b7756d7
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 20 deletions.
21 changes: 1 addition & 20 deletions apps/hpc-ftsadmin/src/app/utils/codecs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,26 +11,7 @@ import {
} from './table-headers';

const ROWS_PER_PAGE_OPTIONS = [10, 25, 50, 100] as const;
const ROWS_PER_PAGE = new t.Type<number, number>(
'ROWS_PER_PAGE',
t.number.is,
(v, c) => {
if (typeof v === 'number') {
return Number.isInteger(v) &&
ROWS_PER_PAGE_OPTIONS.some((row) => row === v)
? t.success(v)
: t.failure(v, c);
} else if (typeof v === 'string') {
return /^[0-9]+$/.test(v) &&
ROWS_PER_PAGE_OPTIONS.some((row) => row === parseInt(v))
? t.success(parseInt(v))
: t.failure(v, c);
} else {
return t.failure(v, c);
}
},
t.identity
);
const ROWS_PER_PAGE = util.validInteger(ROWS_PER_PAGE_OPTIONS);

const PARAMS_CODEC = t.type({
page: util.INTEGER_FROM_STRING,
Expand Down
25 changes: 25 additions & 0 deletions libs/hpc-data/src/lib/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,31 @@ export const POSITIVE_INTEGER_FROM_STRING = new t.Type<number, number>(
t.identity
);

/**
* Accepts either an integer, or a string of an integer, that is contained in
* `integerOptions`. serializes to a number.
*/
export const validInteger = (integerOptions: readonly number[]) =>
new t.Type<number, number>(
'VALID_INTEGER',
t.number.is,
(v, c) => {
if (typeof v === 'number') {
return Number.isInteger(v) && integerOptions.some((row) => row === v)
? t.success(v)
: t.failure(v, c);
} else if (typeof v === 'string') {
return /^\d+$/.test(v) &&
integerOptions.some((row) => row === parseInt(v))
? t.success(parseInt(v))
: t.failure(v, c);
} else {
return t.failure(v, c);
}
},
t.identity
);

/**
* Accepts either a number, or a string of a number, serializes to a number type.
*/
Expand Down

0 comments on commit b7756d7

Please sign in to comment.