Utils: Extract getServerVersionFromPackageJson into own file

We need this function in at least on other part of the application so extracting it into an util file was only logical.

Signed-off-by: Philip Molares <philip.molares@udo.edu>
This commit is contained in:
Philip Molares 2021-03-01 20:52:46 +01:00
parent 6fab7583f0
commit 942cb44e05
2 changed files with 36 additions and 28 deletions

View file

@ -5,34 +5,8 @@
*/ */
import { Injectable } from '@nestjs/common'; import { Injectable } from '@nestjs/common';
import { promises as fs } from 'fs'; import { ServerStatusDto } from './server-status.dto';
import { join as joinPath } from 'path'; import { getServerVersionFromPackageJson } from '../utils/serverVersion';
import { ServerStatusDto, ServerVersion } from './server-status.dto';
let versionCache: ServerVersion;
async function getServerVersionFromPackageJson(): Promise<ServerVersion> {
if (versionCache === null) {
const rawFileContent: string = await fs.readFile(
joinPath(__dirname, '../../package.json'),
{ encoding: 'utf8' },
);
// TODO: Should this be validated in more detail?
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const packageInfo: { version: string } = JSON.parse(rawFileContent);
const versionParts: number[] = packageInfo.version
.split('.')
.map((x) => parseInt(x, 10));
versionCache = {
major: versionParts[0],
minor: versionParts[1],
patch: versionParts[2],
preRelease: 'dev', // TODO: Replace this?
};
}
return versionCache;
}
@Injectable() @Injectable()
export class MonitoringService { export class MonitoringService {

View file

@ -0,0 +1,34 @@
/*
* SPDX-FileCopyrightText: 2021 The HedgeDoc developers (see AUTHORS file)
*
* SPDX-License-Identifier: AGPL-3.0-only
*/
import { ServerVersion } from '../monitoring/server-status.dto';
import { promises as fs } from 'fs';
import { join as joinPath } from 'path';
let versionCache: ServerVersion;
export async function getServerVersionFromPackageJson(): Promise<ServerVersion> {
if (versionCache === null) {
const rawFileContent: string = await fs.readFile(
joinPath(__dirname, '../../package.json'),
{ encoding: 'utf8' },
);
// TODO: Should this be validated in more detail?
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const packageInfo: { version: string } = JSON.parse(rawFileContent);
const versionParts: number[] = packageInfo.version
.split('.')
.map((x) => parseInt(x, 10));
versionCache = {
major: versionParts[0],
minor: versionParts[1],
patch: versionParts[2],
preRelease: 'dev', // TODO: Replace this?
};
}
return versionCache;
}