Skip to content

Commit

Permalink
feat: ✨ add isCuid validation and types (#11)
Browse files Browse the repository at this point in the history
Co-authored-by: Ben Wilson <[email protected]>
  • Loading branch information
yousif-bugsnag and gingerbenw authored Apr 16, 2024
1 parent 8fa65dd commit 7d6d5df
Show file tree
Hide file tree
Showing 4 changed files with 33 additions and 3 deletions.
5 changes: 3 additions & 2 deletions cuid.d.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
declare module '@bugsnag/cuid' {
function cuid(): string
export function fingerprint(): string
export function isCuid(value: unknown): value is string

export default cuid
export default function cuid(): string
}
4 changes: 3 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
*/

var fingerprint = require('./lib/fingerprint.js');
var isCuid = require('./lib/is-cuid.js');
var pad = require('./lib/pad.js');

var c = 0,
Expand Down Expand Up @@ -38,7 +39,7 @@ function cuid () {
// timestamp
// warning: this exposes the exact date and time
// that the uid was created.
timestamp = (new Date().getTime()).toString(base),
timestamp = new Date().getTime().toString(base),

// Prevent same-machine collisions.
counter = pad(safeCounter().toString(base), blockSize),
Expand All @@ -55,5 +56,6 @@ function cuid () {
}

cuid.fingerprint = fingerprint;
cuid.isCuid = isCuid;

module.exports = cuid;
8 changes: 8 additions & 0 deletions lib/is-cuid.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
/**
* Check the provided value is a valid device id
* @param {unknown} value
* @returns
*/
module.exports = function isCuid (value) {
return typeof value === 'string' && (/^c[a-z0-9]{20,32}$/).test(value);
};
19 changes: 19 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -46,3 +46,22 @@ describe('cuid collisions', function () {
expect(collisionTest(cuid)).toBe(true);
});
});

describe('isCuid()', function () {
it('should return true for generated cuids', function () {
expect(cuid.isCuid(cuid())).toBe(true);
});

it('should return false for strings that are too short', function () {
expect(cuid.isCuid('cuidistooshort')).toBe(false);
});

it('should return false for strings that are too long', function () {
expect(cuid.isCuid('cuidismorethan32characterssoisnotvalid')).toBe(false);
});

it('should return false for strings that do not match the format', function () {
expect(cuid.isCuid('doesnotbeginwithacsoisinvalid')).toBe(false);
expect(cuid.isCuid('contains-invalid-characters')).toBe(false);
});
});

0 comments on commit 7d6d5df

Please sign in to comment.