Added id to storystore

This commit is contained in:
Tom Coleman 2018-12-21 15:26:35 +11:00
parent 6e1bed8cb7
commit dbbd06173f
2 changed files with 67 additions and 0 deletions

View File

@ -0,0 +1,29 @@
// NOTE: this file is common to both `lib/ui` (manager) and `lib/core` (preview).
// For now it is reproduced in both places (ick) rather than create a new package.
// We should figure out what we are doing here.
// Create a id/slug compatible string from an arbitrary string. We:
// 1. replace all non-alphanumerics with '-', and downcase.
// 2. replace all runs of '-' with a single '-',
// except if they are at the end, in which case, replace them with ''
function sanitize(string) {
return string
.toLowerCase()
.replace(/[^a-z0-9-]/g, '-')
.replace(/-+/g, '-')
.replace(/^-+/, '')
.replace(/-+$/, '');
}
function sanitizeSafe(string, part) {
const sanitized = sanitize(string);
if (sanitized === '') {
throw new Error(`Invalid ${part} '${string}', must include alphanumeric characters`);
}
return sanitized;
}
export default function toId(kind, story) {
return `${sanitizeSafe(kind, 'kind')}--${sanitizeSafe(story, 'story')}`;
}

View File

@ -0,0 +1,38 @@
import toId from './id';
describe('toId', () => {
[
// name, kind, story, output
['handles simple cases', 'kind', 'story', 'kind--story'],
['handles basic substitution', 'a b$c?d😀e', '1-2:3', 'a-b-c-d-e--1-2-3'],
['handles runs of non-url chars', 'a?&*b', 'story', 'a-b--story'],
['removes non-url chars from start and end', '?ab-', 'story', 'ab--story'],
['downcases', 'KIND', 'STORY', 'kind--story'],
].forEach(([name, kind, story, output]) => {
it(name, () => {
expect(toId(kind, story)).toBe(output);
});
});
it('does not allow kind with *no* url chars', () => {
expect(() => toId('?', 'asdf')).toThrow(
`Invalid kind '?', must include alphanumeric characters`
);
});
it('does not allow empty kind', () => {
expect(() => toId('', 'asdf')).toThrow(`Invalid kind '', must include alphanumeric characters`);
});
it('does not allow story with *no* url chars', () => {
expect(() => toId('kind', '?')).toThrow(
`Invalid story '?', must include alphanumeric characters`
);
});
it('does not allow empty story', () => {
expect(() => toId('kind', '')).toThrow(
`Invalid story '', must include alphanumeric characters`
);
});
});