Skip to content

Commit

Permalink
fix: 🚨 eslint auto fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
DerZade committed Oct 6, 2023
1 parent c634587 commit be5e426
Show file tree
Hide file tree
Showing 11 changed files with 56 additions and 55 deletions.
6 changes: 3 additions & 3 deletions api/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { existsSync } from 'fs';
// eslint-disable-next-line import/no-duplicates
import * as express from 'express';
// eslint-disable-next-line import/no-duplicates
import { Request, Response, NextFunction } from 'express';
import { type Request, type Response, type NextFunction } from 'express';

import * as bodyParser from 'body-parser';
import * as morgan from 'morgan';
Expand Down Expand Up @@ -64,9 +64,9 @@ app.get('/sitemap.xml', async (req, res) => {
// frontend
if (existsSync(join(__dirname, '../frontend'))) {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const assetsManifest: { [originalFilePath: string]: string } = require(join(__dirname, '../frontend', 'assets-manifest.json'));
const assetsManifest: Record<string, string> = require(join(__dirname, '../frontend', 'assets-manifest.json'));

const cacheHeaders: { [path: string]: string|undefined } = {};
const cacheHeaders: Record<string, string | undefined> = {};

for (const originalFilePath in assetsManifest) {
if (Object.prototype.hasOwnProperty.call(assetsManifest, originalFilePath)) {
Expand Down
14 changes: 7 additions & 7 deletions api/src/models/container.model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,17 +40,17 @@ export default class Container extends Model<Container> {
@Default(null)
@AllowNull
@Column(DataType.TEXT)
public headerColor: string|null;
public headerColor: string | null;

@Default(null)
@AllowNull
@Column(DataType.TEXT)
public headerImage: string|null;
public headerImage: string | null;

@Default(null)
@AllowNull
@Column(DataType.TEXT)
public pinnedImage: string|null;
public pinnedImage: string | null;

@Default(0)
@Column(DataType.INTEGER)
Expand All @@ -67,13 +67,13 @@ export default class Container extends Model<Container> {
@AfterUpdate
@AfterCreate
@AfterDestroy
static updatePageUpdatedAt(instance: Container): Promise<void> {
return (Page.findByPk(instance.pageSlug) as Promise<Page|null>).then((page): Promise<void> => {
if (page === null) return Promise.resolve();
static async updatePageUpdatedAt (instance: Container): Promise<void> {
await (Page.findByPk(instance.pageSlug)).then(async (page): Promise<void> => {
if (page === null) { await Promise.resolve(); return; }

page.changed('updatedAt', true);

return page.save();
return await page.save();
});
}
}
28 changes: 14 additions & 14 deletions api/src/utils/EventsService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,44 +2,44 @@ import * as equals from 'fast-deep-equal';
import fetch from 'node-fetch';

export interface ArmaEvent {
date: Date;
title: string;
url: string;
attendance: [number, number];
date: Date
title: string
url: string
attendance: [number, number]
}

export class ArmaEventsService {
private static readonly ATTENDANCE_PLUGIN_INTRODUCTION = 1483833600000;
private static readonly FORUM_URI = 'https://forum.gruppe-adler.de';
private static readonly TOPIC_TITLE_REGEX = /^\d{4}-\d{2}-\d{2}\s*,(\s*\w+\s*,)?\s*/i;

private static instance: ArmaEventsService|null = null;
private static instance: ArmaEventsService | null = null;

private cachedEvents: ArmaEvent[] = [];
private lastModified: Date = new Date(0);

// this constructor is actually important to make sure it is private (singleton pattern)
// eslint-disable-next-line no-useless-constructor, @typescript-eslint/no-empty-function
private constructor() {
private constructor () {
this.cacheEvents();

// fetch new events every half an hour
setInterval(this.cacheEvents.bind(this), 1000 * 60 * 30);
}

public static getInstance(): ArmaEventsService {
public static getInstance (): ArmaEventsService {
if (this.instance === null) {
this.instance = new ArmaEventsService();
}

return this.instance;
}

public async getEvents(): Promise<{ events: ArmaEvent[], lastModified: Date }> {
public async getEvents (): Promise<{ events: ArmaEvent[], lastModified: Date }> {
return { events: this.cachedEvents, lastModified: this.lastModified };
}

public async cacheEvents(): Promise<void> {
public async cacheEvents (): Promise<void> {
const events = await this.fetchEvents();

if (!equals(this.cachedEvents, events)) {
Expand All @@ -48,12 +48,12 @@ export class ArmaEventsService {
}
}

private async fetchEvents(): Promise<ArmaEvent[]> {
private async fetchEvents (): Promise<ArmaEvent[]> {
const response = await fetch(`${ArmaEventsService.FORUM_URI}/api/events/cid-3`);
if (!response.ok) {
throw new Error(`Error while trying to fetch events. Forum API responded with status code ${response.status}.`);
}
const { topics } = await response.json() as { topics: Array<{ slug: string; titleRaw: string; tid: number; deleted: 1|0; timestamp: number }> };
const { topics } = await response.json() as { topics: Array<{ slug: string, titleRaw: string, tid: number, deleted: 1 | 0, timestamp: number }> };

const rawEvents: Array<Omit<ArmaEvent, 'attendance'> & { tid: number }> = [];
for (const topic of topics) {
Expand Down Expand Up @@ -83,9 +83,9 @@ export class ArmaEventsService {
const firstFutureEvent = sortedEvents.findIndex(e => ArmaEventsService.isInFuture(e.date)) + 1;
const filteredEvents = sortedEvents.slice(0, firstFutureEvent > 0 ? firstFutureEvent : sortedEvents.length).reverse().slice(0, 10);

const promises = filteredEvents.map(({ tid, ...rest }) => ArmaEventsService.fetchAttendance(tid).then((attendance): ArmaEvent => ({ ...rest, attendance })));
const promises = filteredEvents.map(async ({ tid, ...rest }) => await ArmaEventsService.fetchAttendance(tid).then((attendance): ArmaEvent => ({ ...rest, attendance })));

return Promise.all(promises);
return await Promise.all(promises);
}

/**
Expand Down Expand Up @@ -118,7 +118,7 @@ export class ArmaEventsService {
if (!response.ok) {
throw new Error(`Error while trying to fetch attendance for topic ${tid}. Forum API responded with status code ${response.status}.`);
}
const { attendants } = await response.json() as { attendants: Array<{ probability: 0|0.5|1 }> };
const { attendants } = await response.json() as { attendants: Array<{ probability: 0 | 0.5 | 1 }> };

let firm = 0;
let maybe = 0;
Expand Down
2 changes: 1 addition & 1 deletion api/src/utils/ResponseError.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ export default class ReponseError extends Error {

public status: number;

constructor(status: number, msg?: string) {
constructor (status: number, msg?: string) {
super(msg);
this.status = status;
}
Expand Down
14 changes: 7 additions & 7 deletions api/src/utils/UploadService.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { existsSync, mkdirSync, writeFileSync, unlinkSync } from 'fs';

export class UploadService {
private static instance: UploadService|null = null;
private static instance: UploadService | null = null;
public static readonly UPLOADS_BASE_PATH = 'data/uploads';

private static readonly MINE_TYPES = new Map<string, string>([
Expand All @@ -13,26 +13,26 @@ export class UploadService {
['image/bmp', 'bmp']
]);

public static get ALLOWED_MIME_TYPES(): string[] {
public static get ALLOWED_MIME_TYPES (): string[] {
return Array.from(this.MINE_TYPES.keys());
}

private constructor() {
private constructor () {
// create directory if it doesn't exist already
if (!existsSync(UploadService.UPLOADS_BASE_PATH)) {
mkdirSync(UploadService.UPLOADS_BASE_PATH);
}
}

public static getInstance(): UploadService {
public static getInstance (): UploadService {
if (this.instance === null) {
this.instance = new UploadService();
}

return this.instance;
}

public saveFile(buffer: Buffer, mimeType: string): string {
public saveFile (buffer: Buffer, mimeType: string): string {
if (!UploadService.MINE_TYPES.has(mimeType.toLowerCase())) throw new Error(`MIME type '${mimeType}' is not allowed`);

const fileEnding: string = UploadService.MINE_TYPES.get(mimeType.toLowerCase());
Expand All @@ -46,13 +46,13 @@ export class UploadService {
return `${name}.${fileEnding}`;
}

public removeFile(name: string): void {
public removeFile (name: string): void {
if (!existsSync(`${UploadService.UPLOADS_BASE_PATH}/${name}`)) return;

unlinkSync(`${UploadService.UPLOADS_BASE_PATH}/${name}`);
}

private static randomName(): string {
private static randomName (): string {
return (Math.random().toString(36).substr(2)) + (Math.random().toString(36).substr(2));
}
}
6 changes: 3 additions & 3 deletions api/src/utils/express.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Request, Response, NextFunction, RequestHandler } from 'express';
import { type Request, type Response, type NextFunction, type RequestHandler } from 'express';
import { validationResult } from 'express-validator';
import ResponseError from './ResponseError';

Expand All @@ -15,7 +15,7 @@ export const globalErrorHandler = (err: unknown, req: Request, res: Response, ne
}

let status = 500;
let msg: undefined|string;
let msg: undefined | string;

if (err instanceof ResponseError) {
status = err.status;
Expand All @@ -33,7 +33,7 @@ export const globalErrorHandler = (err: unknown, req: Request, res: Response, ne
}
};

export function return422(req: Request, res: Response, next: NextFunction): void {
export function return422 (req: Request, res: Response, next: NextFunction): void {
const errors = validationResult(req);
if (!errors.isEmpty()) {
res.status(422).json({ errors: errors.array() });
Expand Down
10 changes: 5 additions & 5 deletions api/src/utils/sitemap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { SitemapStream, streamToPromise } from 'sitemap';
import { createGzip } from 'zlib';
import { Page } from '../models';

let cachedSitemap: Buffer|null = null;
let cachedSitemap: Buffer | null = null;

const BUILD_TIME_PATH = '/build-date.txt';
let buildTime = new Date(0);
Expand All @@ -22,11 +22,11 @@ Page.addHook('afterCreate', cacheSitemap);
Page.addHook('afterDestroy', cacheSitemap);
Page.addHook('afterUpdate', cacheSitemap);

async function cacheSitemap(): Promise<void> {
async function cacheSitemap (): Promise<void> {
cachedSitemap = await generateSitemap();
}

async function generateSitemap(): Promise<Buffer> {
async function generateSitemap (): Promise<Buffer> {
const smStream = new SitemapStream({ hostname: 'https://gruppe-adler.de/' });
const pipeline = smStream.pipe(createGzip());

Expand All @@ -43,10 +43,10 @@ async function generateSitemap(): Promise<Buffer> {

const prom = streamToPromise(pipeline);
smStream.end();
return prom;
return await prom;
}

export async function getSitemap(): Promise<Buffer> {
export async function getSitemap (): Promise<Buffer> {
await initialCachePromise;
return cachedSitemap;
}
14 changes: 7 additions & 7 deletions api/src/utils/sso.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Request, Response, NextFunction } from 'express/index';
import { type Request, type Response, type NextFunction } from 'express/index';

import fetch from 'node-fetch';
import { globalErrorHandler } from './express';
Expand All @@ -8,11 +8,11 @@ import ReponseError from './ResponseError';
const config = require('../../config/config.json');

interface SSOUser {
admin: boolean;
groups: { tag: string; }[];
admin: boolean
groups: Array<{ tag: string }>
}

async function fetchUser(token: string): Promise<SSOUser|null> {
async function fetchUser (token: string): Promise<SSOUser | null> {
const res = await fetch(`${config.sso.domain}/api/v1/graphql`, {
method: 'POST',
headers: {
Expand All @@ -37,7 +37,7 @@ async function fetchUser(token: string): Promise<SSOUser|null> {

if (!res.ok) throw new ReponseError(401);

const json = await res.json() as { data: { authenticate: SSOUser|null } };
const json = await res.json() as { data: { authenticate: SSOUser | null } };

return json.data.authenticate;
}
Expand All @@ -58,7 +58,7 @@ async function validateToken (token: string) {
if (!admin && !isInGroup) throw new ReponseError(403);
}

function extractToken(req: Request): string {
function extractToken (req: Request): string {
if (req.cookies[config.sso.cookiename]) {
return req.cookies[config.sso.cookiename];
}
Expand All @@ -73,7 +73,7 @@ function extractToken(req: Request): string {
throw new Error('Couldn\'t find token to extract');
}

export async function ssoCheckAuthorized(req: Request, res: Response, next: NextFunction): Promise<void> {
export async function ssoCheckAuthorized (req: Request, res: Response, next: NextFunction): Promise<void> {
let token: string;
try {
token = extractToken(req);
Expand Down
6 changes: 3 additions & 3 deletions api/src/v1/routes/container.router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ const defaultContainerRules = [
body('index').optional().isInt().toInt()
];

type OptionalContainerFields = Partial<Pick<Container, 'heading'|'footer'|'content'|'headerColor'|'headerImage'|'pinnedImage'|'index'>>;
type OptionalContainerFields = Partial<Pick<Container, 'heading' | 'footer' | 'content' | 'headerColor' | 'headerImage' | 'pinnedImage' | 'index'>>;

const containerRouter = Router();

Expand All @@ -41,7 +41,7 @@ containerRouter.put('/:id', [
], wrapAsync(async (req, res) => {
const { id, ...updateData } = matchedData(req) as OptionalContainerFields & Partial<Pick<Container, 'pageSlug'>> & Pick<Container, 'id'>;

const container: Container|null = await Container.findByPk(id);
const container: Container | null = await Container.findByPk(id);

if (container === null) {
throw new ReponseError(404, `Container with id '${id}' not found.`);
Expand All @@ -59,7 +59,7 @@ containerRouter.delete('/:id', [
], wrapAsync(async (req, res) => {
const { id } = matchedData(req) as { id: number };

const container: Container|null = await Container.findByPk(id);
const container: Container | null = await Container.findByPk(id);

if (container === null) {
throw new ReponseError(404, `Container with id '${id}' not found.`);
Expand Down
10 changes: 5 additions & 5 deletions api/src/v1/routes/page.router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ const pageRouter = Router();
pageRouter.get('/*', wrapAsync(async (req, res) => {
const slug = req.path;

const page = await Page.findByPk(slug) as Page|null;
const page = await Page.findByPk(slug);

if (page === null) {
throw new ReponseError(404, `Page with slug '${slug}' not found.`);
Expand All @@ -31,9 +31,9 @@ pageRouter.put('/*', [
], wrapAsync(async (req, res) => {
const slug = req.path;

const updateData = matchedData(req) as Partial<Pick<Page, 'toc'|'description'|'title'|'priority'>>;
const updateData = matchedData(req) as Partial<Pick<Page, 'toc' | 'description' | 'title' | 'priority'>>;

const page: Page|null = await Page.findByPk(slug);
const page: Page | null = await Page.findByPk(slug);

if (page === null) {
throw new ReponseError(404, `Page with slug '${slug}' not found.`);
Expand All @@ -53,7 +53,7 @@ pageRouter.post('/', [
body('priority').optional().isFloat({ min: 0, max: 1 }).toFloat(),
return422
], wrapAsync(async (req, res) => {
const data = matchedData(req) as Partial<Pick<Page, 'toc'|'description'|'title'|'priority'>> & Pick<Page, 'slug'>;
const data = matchedData(req) as Partial<Pick<Page, 'toc' | 'description' | 'title' | 'priority'>> & Pick<Page, 'slug'>;

const page = await Page.create(data);

Expand All @@ -65,7 +65,7 @@ pageRouter.delete('/*', [
], wrapAsync(async (req, res) => {
const slug = req.path;

const page: Page|null = await Page.findByPk(slug);
const page: Page | null = await Page.findByPk(slug);

if (page === null) {
throw new ReponseError(404, `Container with slug '${slug}' not found.`);
Expand Down
1 change: 1 addition & 0 deletions api/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
"target": "es6",
"sourceMap": true,
"outDir": "./build",
"strictNullChecks": true
},
"exclude": [
"node_modules"
Expand Down

0 comments on commit be5e426

Please sign in to comment.