ln/app/server/helpers.ts

34 lines
1,012 B
TypeScript

import { RatingType as RatingTypeSchema } from '@generated/types';
import { Descendant, Text } from 'slate';
import { IdentityContext } from './identity';
export function ensureIdentity(
identity: IdentityContext['identity']
): asserts identity is NonNullable<IdentityContext['identity']> {
if (identity == null) throw new Error('Unauthorized.');
}
export function countWords(descendants: Descendant[]): number {
let wordCount = 0;
function traverse(nodes: Descendant[]) {
for (const node of nodes) {
if (Text.isText(node)) {
const words = node.text.trim().split(/\s+/).filter(Boolean);
wordCount += words.length;
} else if ('children' in node) {
traverse(node.children);
}
}
}
traverse(descendants);
return wordCount;
}
export function ensureRatingType(value: string): asserts value is RatingTypeSchema {
if (value === RatingTypeSchema.Up) return;
if (value === RatingTypeSchema.Down) return;
throw new Error('Invalid rating type');
}