1
0
mirror of https://github.com/kremalicious/astro-redirect-from.git synced 2024-11-22 09:57:03 +01:00

prependForwardSlash helper

This commit is contained in:
Matthias Kretschmann 2023-09-24 11:42:29 +01:00
parent d2751a5855
commit 7fb9b2f60d
Signed by: m
GPG Key ID: 606EEEF3C479A91F
3 changed files with 34 additions and 3 deletions

View File

@ -1,15 +1,15 @@
import type { Redirects } from './index.js'
import { prependForwardSlash } from './utils.js'
export function createRedirect(
redirects: Redirects,
redirectFrom: string[],
postSlug: string
) {
// Prepend all slugs with a slash if not present
if (!postSlug.startsWith('/')) postSlug = `/${postSlug}`
postSlug = prependForwardSlash(postSlug)
for (let slug of redirectFrom) {
if (!slug.startsWith('/')) slug = `/${slug}`
slug = prependForwardSlash(slug)
redirects[slug] = postSlug
}

View File

@ -38,3 +38,7 @@ export async function writeJson<T>(path: PathLike, data: T) {
encoding: 'utf-8'
})
}
export function prependForwardSlash(str: string) {
return str.startsWith('/') ? str : '/' + str
}

View File

@ -4,6 +4,7 @@ import {
getMarkdownFiles,
getMarkdownFrontmatter,
getSlugFromFilePath,
prependForwardSlash,
writeJson
} from '../src/utils'
@ -63,3 +64,29 @@ describe('writeJson', () => {
expect(parsedContent).toEqual(testData)
})
})
describe('prependForwardSlash', () => {
it('should prepend a forward slash if it does not start with one', () => {
const stringWithSlash = '/alreadyHasSlash'
const result1 = prependForwardSlash(stringWithSlash)
expect(result1).toBe('/alreadyHasSlash')
})
it('should prepend a forward slash', () => {
const stringWithoutSlash = 'noSlashAtStart'
const result2 = prependForwardSlash(stringWithoutSlash)
expect(result2).toBe('/noSlashAtStart')
})
it('should return a single forward slash if the input string is empty', () => {
const emptyString = ''
const result3 = prependForwardSlash(emptyString)
expect(result3).toBe('/')
})
it('should return a single forward slash if a slash is passed', () => {
const string = '/'
const result4 = prependForwardSlash(string)
expect(result4).toBe('/')
})
})