typedserver/ts/servertools/classes.sitemap.ts

69 lines
1.9 KiB
TypeScript
Raw Normal View History

2023-03-30 13:15:48 +00:00
import { Server } from './classes.server.js';
import { Handler } from './classes.handler.js';
2024-02-20 16:30:46 +00:00
import * as plugins from '../plugins.js';
2023-08-03 18:50:18 +00:00
import { type IUrlInfo } from '@push.rocks/smartsitemap';
2023-03-30 13:15:48 +00:00
export class Sitemap {
public smartexpressRef: Server;
public smartSitemap = new plugins.smartsitemap.SmartSitemap();
public urls: plugins.smartsitemap.IUrlInfo[] = [];
/**
* handles the normal sitemap request
*/
public sitemapHandler = new Handler('GET', async (req, res) => {
const sitemapXmlString = await this.smartSitemap.createSitemapFromUrlInfoArray(this.urls);
res.type('.xml');
res.write(sitemapXmlString);
res.end();
});
/**
* handles the sitemap-news request
*/
public sitemapNewsHandler = new Handler('GET', async (req, res) => {
if (!this.smartexpressRef.options.articleGetterFunction) {
res.status(500);
res.write('no article getter function defined.');
res.end();
return;
}
const sitemapNewsXml = await this.smartSitemap.createSitemapNewsFromArticleArray(
await this.smartexpressRef.options.articleGetterFunction()
);
res.type('.xml');
res.write(sitemapNewsXml);
res.end();
});
constructor(smartexpressRefArg: Server) {
this.smartexpressRef = smartexpressRefArg;
this.smartexpressRef.addRouteBefore('/sitemap', this.sitemapHandler);
this.smartexpressRef.addRouteBefore('/sitemap-news', this.sitemapNewsHandler);
// lets set the default url
if (this.smartexpressRef.options.domain) {
this.urls.push({
url: `https://${this.smartexpressRef.options.domain}/`,
timestamp: Date.now(),
frequency: 'daily',
});
}
}
/**
* replaces the current urlsArray
* @param urlsArg
*/
public replaceUrls(urlsArg: IUrlInfo[]) {
this.urls = urlsArg;
}
/**
* adds urls to the current set of urls
*/
public addUrls(urlsArg: IUrlInfo[]) {
this.urls = this.urls.concat(this.urls, urlsArg);
}
}