Skip to content

Commit

Permalink
update
Browse files Browse the repository at this point in the history
  • Loading branch information
yoshinorin committed Jan 4, 2024
1 parent b76f90e commit e0ed94c
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
22 changes: 22 additions & 0 deletions __tests__/unit/utils/slug.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { expect, test } from "vitest";
import { sluggize } from "../../../src/utils/slug";

test('should sluggize from string array - without prefix and fallback option', () => {
expect(sluggize(['foo', 'bar'])).toEqual('/foo/bar');
});

test('should sluggize from number array - without prefix and fallback option', () => {
expect(sluggize([1, 2])).toEqual('/1/2');
});

test('should sluggize from array - without fallback option', () => {
expect(sluggize(['foo', 'bar'], '_prefix')).toEqual('/_prefix/foo/bar');
});

test('should sluggize returns fallback (undefined) if slug can not convert to array', () => {
expect(sluggize({'hoge': 'piyo'}, '_prefix')).toEqual(undefined);
});

test('should sluggize returns fallback string if slug can not convert to array', () => {
expect(sluggize({'hoge': 'piyo'}, '_prefix', 'fallback_str')).toEqual('fallback_str');
});
20 changes: 20 additions & 0 deletions src/utils/slug.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
export function sluggize(
slug: any, // NOTE: Next.js request context is any.
prefix: string | undefined = undefined,
fallback: string | undefined = undefined
) {
try {
console.log()
if (slug instanceof Array) {
const p = prefix === undefined ? undefined : '/' + prefix;
const s = slug as Array<string>;
const arr = [p].concat(s);
return arr.join('/');
} else {
return fallback;
}
} catch {
return fallback;
}
}

0 comments on commit e0ed94c

Please sign in to comment.