Skip to content

Commit

Permalink
[Fix] Wrong field order inside <url>
Browse files Browse the repository at this point in the history
Fix: #345
  • Loading branch information
iamvishnusankar committed Jun 3, 2022
1 parent aa5e890 commit 94bdf5b
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 9 deletions.
40 changes: 32 additions & 8 deletions packages/next-sitemap/src/builders/sitemap-builder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,38 +28,62 @@ export class SitemapBuilder {
</sitemapindex>`
}

/**
* Normalize sitemap field keys to stay consistent with <xsd:sequence> order
* @link https://www.w3schools.com/xml/el_sequence.asp
* @link https://github.com/iamvishnusankar/next-sitemap/issues/345
* @param x
* @returns
*/
normalizeSitemapField(x: ISitemapField) {
const { loc, lastmod, changefreq, priority, ...restProps } = x

// Return keys in following order
return {
loc,
lastmod,
changefreq,
priority,
...restProps,
}
}

/**
* Generates sitemap.xml
* @param fields
* @returns
*/
buildSitemapXml(fields: ISitemapField[]): string {
const content = fields
.map((fieldData) => {
const field: Array<string> = []
.map((x: ISitemapField) => {
// Normalize sitemap field keys to stay consistent with <xsd:sequence> order
const filed = this.normalizeSitemapField(x)

// Field array to keep track of properties
const fieldArr: Array<string> = []

// Iterate all object keys and key value pair to field-set
for (const key of Object.keys(fieldData)) {
for (const key of Object.keys(filed)) {
// Skip reserved keys
if (['trailingSlash'].includes(key)) {
continue
}

if (fieldData[key]) {
if (filed[key]) {
if (key !== 'alternateRefs') {
field.push(`<${key}>${fieldData[key]}</${key}>`)
fieldArr.push(`<${key}>${filed[key]}</${key}>`)
} else {
const altRefField = this.buildAlternateRefsXml(
fieldData.alternateRefs
filed.alternateRefs
)

field.push(altRefField)
fieldArr.push(altRefField)
}
}
}

// Append previous value and return
return `<url>${field.join('')}</url>\n`
return `<url>${fieldArr.join('')}</url>\n`
})
.join('')

Expand Down
2 changes: 1 addition & 1 deletion packages/next-sitemap/src/utils/defaults.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@ export const defaultSitemapTransformer = async (
): Promise<ISitemapField> => {
return {
loc,
lastmod: config?.autoLastmod ? new Date().toISOString() : undefined,
changefreq: config?.changefreq,
priority: config?.priority,
lastmod: config?.autoLastmod ? new Date().toISOString() : undefined,
alternateRefs: config.alternateRefs ?? [],
trailingSlash: config?.trailingSlash,
}
Expand Down

0 comments on commit 94bdf5b

Please sign in to comment.