infer return type of functions

This commit is contained in:
Thomas Ruoff
2021-03-22 23:14:48 +01:00
parent 3cf2aff832
commit 9fe3fffb86
16 changed files with 54 additions and 54 deletions

View File

@@ -18,10 +18,10 @@ export interface Bill {
export interface BillDocument export interface BillDocument
extends Bill, extends Bill,
mongoose.SchemaTimestampsConfig, mongoose.SchemaTimestampsConfig,
mongoose.Document {} mongoose.Document { }
export interface BillModel extends mongoose.Model<BillDocument> {} export interface BillModel extends mongoose.Model<BillDocument> { }
const BillSchema = new mongoose.Schema<BillDocument>( const BillSchema = new mongoose.Schema<BillDocument>(
{ {
@@ -29,7 +29,7 @@ const BillSchema = new mongoose.Schema<BillDocument>(
type: Number, type: Number,
required: true, required: true,
validate: { validate: {
validator: function (v: number) { validator: function(v: number): boolean {
const bill = this as BillDocument const bill = this as BillDocument
return v <= bill.milageEnd return v <= bill.milageEnd
@@ -43,7 +43,7 @@ const BillSchema = new mongoose.Schema<BillDocument>(
required: true, required: true,
validate: { validate: {
validator: function (v: number) { validator: function(v: number): boolean {
const bill = this as BillDocument const bill = this as BillDocument
return v >= bill.milageStart return v >= bill.milageStart
@@ -77,12 +77,12 @@ const BillSchema = new mongoose.Schema<BillDocument>(
} }
) )
BillSchema.virtual('milage').get(function () { BillSchema.virtual('milage').get(function(): number {
const bill = this as BillDocument const bill = this as BillDocument
return bill.milageEnd - bill.milageStart return bill.milageEnd - bill.milageStart
}) })
BillSchema.virtual('total').get(function () { BillSchema.virtual('total').get(function(): number {
const bill = this as BillDocument const bill = this as BillDocument
return getBillTotal(bill) return getBillTotal(bill)

View File

@@ -22,8 +22,8 @@ export interface Booking {
export interface BookingDocument export interface BookingDocument
extends Booking, extends Booking,
mongoose.Document, mongoose.Document,
mongoose.SchemaTimestampsConfig {} mongoose.SchemaTimestampsConfig { }
export interface BookingModel extends mongoose.Model<BookingDocument> { export interface BookingModel extends mongoose.Model<BookingDocument> {
findBookedDays(uuidsToIngore?: string[]): Promise<string[]> findBookedDays(uuidsToIngore?: string[]): Promise<string[]>
@@ -52,10 +52,10 @@ const BookingSchema = new mongoose.Schema<BookingDocument>(
required: true, required: true,
get: dateFormatBackend, get: dateFormatBackend,
validate: { validate: {
validator: function (v: Date) { validator: function(v: Date): boolean {
return v >= nowInTz() return v >= nowInTz()
}, },
message: (props: { value: Date }) => `${props.value} is in the past`, message: (props: { value: Date }): string => `${props.value} is in the past`,
}, },
}, },
endDate: { endDate: {
@@ -63,27 +63,27 @@ const BookingSchema = new mongoose.Schema<BookingDocument>(
required: false, required: false,
get: dateFormatBackend, get: dateFormatBackend,
validate: { validate: {
validator: function (v: Date) { validator: function(v: Date): boolean {
return v >= nowInTz() return v >= nowInTz()
}, },
message: (props: { value: Date }) => `${props.value} is in the past`, message: (props: { value: Date }): string => `${props.value} is in the past`,
}, },
}, },
days: { days: {
type: [String], type: [String],
required: true, required: true,
validate: { validate: {
validator: async function (days: string[]) { validator: async function(days: string[]): Promise<boolean> {
const booking = this as Booking const booking = this as Booking
const uuid = booking.uuid && [booking.uuid] const uuid = booking.uuid && [booking.uuid]
const bookedDays = await getBookedDays(uuid) const bookedDays = await getBookedDays(uuid)
const doubleBookedDays = days.filter((day: string) => const doubleBookedDays = days.filter((day: string): boolean =>
bookedDays.includes(day) bookedDays.includes(day)
) )
return doubleBookedDays.length === 0 return doubleBookedDays.length === 0
}, },
message: (props: { value: string[] }) => message: (props: { value: string[] }): string =>
`At least one day is of ${props.value.join(',')} is already booked`, `At least one day is of ${props.value.join(',')} is already booked`,
type: VALIDATION_ERRORS.AT_LEAST_ONE_DAY_BOOKED, type: VALIDATION_ERRORS.AT_LEAST_ONE_DAY_BOOKED,
}, },
@@ -105,7 +105,7 @@ const BookingSchema = new mongoose.Schema<BookingDocument>(
} }
) )
BookingSchema.pre('validate', function (next: () => void) { BookingSchema.pre('validate', function(next: () => void): void {
const booking = this as BookingDocument const booking = this as BookingDocument
booking.days = getDays({ booking.days = getDays({
startDate: new Date(booking.startDate), startDate: new Date(booking.startDate),
@@ -114,7 +114,7 @@ BookingSchema.pre('validate', function (next: () => void) {
next() next()
}) })
BookingSchema.static('findBookedDays', async function ( BookingSchema.static('findBookedDays', async function(
uuidsToIngore: string[] = [] uuidsToIngore: string[] = []
): Promise<string[]> { ): Promise<string[]> {
const model = this as BookingModel const model = this as BookingModel

View File

@@ -1,12 +1,12 @@
import * as mongoose from 'mongoose' import * as mongoose from 'mongoose'
import BookerModel, { Booker } from './booker' import BookerModel, { Booker } from './booker'
import BookingModel, { Booking } from './booking' import BookingModel, { Booking, BookingDocument } from './booking'
import BillModel, { Bill } from './bill' import BillModel, { Bill } from './bill'
import { BOOKING_STATUS } from './enums' import { BOOKING_STATUS } from './enums'
let connectedPromise: Promise<typeof mongoose> let connectedPromise: Promise<typeof mongoose>
function connect() { function connect(): Promise<typeof mongoose> {
if (connectedPromise) { if (connectedPromise) {
return return
} }
@@ -20,12 +20,12 @@ function connect() {
return connectedPromise return connectedPromise
} }
export async function getBookedDays(uuidsToIngore?: string[]) { export async function getBookedDays(uuidsToIngore?: string[]): Promise<string[]> {
await connect() await connect()
return BookingModel.findBookedDays(uuidsToIngore) return BookingModel.findBookedDays(uuidsToIngore)
} }
export async function getBookingByUUID(uuid: string) { export async function getBookingByUUID(uuid: string): Promise<BookingDocument> {
await connect() await connect()
return BookingModel.findOne({ uuid }) return BookingModel.findOne({ uuid })
} }
@@ -33,7 +33,7 @@ export async function getBookingByUUID(uuid: string) {
export async function getBookings({ export async function getBookings({
status = [BOOKING_STATUS.CONFIRMED, BOOKING_STATUS.REQUESTED], status = [BOOKING_STATUS.CONFIRMED, BOOKING_STATUS.REQUESTED],
startDateGreaterThan = '2000-01-01T00:00:00Z', startDateGreaterThan = '2000-01-01T00:00:00Z',
}: { status?: BOOKING_STATUS[]; startDateGreaterThan?: string } = {}) { }: { status?: BOOKING_STATUS[]; startDateGreaterThan?: string } = {}): Promise<BookingDocument[]> {
await connect() await connect()
return await BookingModel.find({ return await BookingModel.find({
status: { $in: status }, status: { $in: status },

View File

@@ -1,4 +1,4 @@
export function getNextSmaller<T>(array: T[], pivot: T) { export function getNextSmaller<T>(array: T[], pivot: T): T {
if (!array || !Array.isArray(array) || !array.length) { if (!array || !Array.isArray(array) || !array.length) {
return null return null
} }
@@ -9,7 +9,7 @@ export function getNextSmaller<T>(array: T[], pivot: T) {
.find((item) => item < pivot) .find((item) => item < pivot)
} }
export function getNextBigger<T>(array: T[], pivot: T) { export function getNextBigger<T>(array: T[], pivot: T): T {
if (!array || !Array.isArray(array) || !array.length) { if (!array || !Array.isArray(array) || !array.length) {
return null return null
} }

View File

@@ -1,11 +1,11 @@
import { MILAGE_TARIFS } from '../db/enums' import { MILAGE_TARIFS } from '../db/enums'
import { AdditionalCost } from '../db/bill' import { AdditionalCost } from '../db/bill'
function roundToCent(amount: number) { function roundToCent(amount: number): number {
return Math.round(amount * 100) / 100 return Math.round(amount * 100) / 100
} }
export function getMilageCosts(tarif: MILAGE_TARIFS, km: number): number { export function getMilageCosts({ tarif, km }: { tarif: MILAGE_TARIFS; km: number }): number {
if (tarif === MILAGE_TARIFS.NOCHARGE) { if (tarif === MILAGE_TARIFS.NOCHARGE) {
return 0 return 0
} }
@@ -56,7 +56,7 @@ export function getBillTotal({
milage?: number milage?: number
additionalCosts: AdditionalCost[] additionalCosts: AdditionalCost[]
}): number { }): number {
const milageCosts = getMilageCosts(tarif, milage) const milageCosts = getMilageCosts({ tarif, km: milage })
const additionalCostsSum = additionalCosts const additionalCostsSum = additionalCosts
.map(({ value }) => value) .map(({ value }) => value)
.reduce((acc: number, value: number) => acc + value, 0) .reduce((acc: number, value: number) => acc + value, 0)

View File

@@ -4,7 +4,7 @@ import { utcToZonedTime } from 'date-fns-tz'
const FRONTEND_FORMAT = 'dd.MM.yyyy' const FRONTEND_FORMAT = 'dd.MM.yyyy'
const BACKEND_FORMAT = 'yyyy-MM-dd' const BACKEND_FORMAT = 'yyyy-MM-dd'
export function daysFormatFrontend(days: string[]) { export function daysFormatFrontend(days: string[]): string {
if (days.length === 0) { if (days.length === 0) {
return '' return ''
} }
@@ -24,7 +24,7 @@ export function getDays({
}: { }: {
startDate: Date startDate: Date
endDate: Date endDate: Date
}) { }): string[] {
let currentDay = new Date(startDate.getTime()) let currentDay = new Date(startDate.getTime())
const days = [dateFormatBackend(currentDay)] const days = [dateFormatBackend(currentDay)]
@@ -40,22 +40,22 @@ export function getDays({
return days return days
} }
function dateFormat(date: Date, formatString: string) { function dateFormat(date: Date, formatString: string): string {
if (!date) { if (!date) {
return null return null
} }
return format(date, formatString) return format(date, formatString)
} }
export function dateFormatBackend(date: Date) { export function dateFormatBackend(date: Date): string {
return dateFormat(date, BACKEND_FORMAT) return dateFormat(date, BACKEND_FORMAT)
} }
export function dateFormatFrontend(date: Date) { export function dateFormatFrontend(date: Date): string {
return dateFormat(date, FRONTEND_FORMAT) return dateFormat(date, FRONTEND_FORMAT)
} }
function dateParse(input: string, formatString: string) { function dateParse(input: string, formatString: string): Date {
const date = parse(input, formatString, new Date()) const date = parse(input, formatString, new Date())
if (date.getTime() !== NaN) { if (date.getTime() !== NaN) {
return date return date
@@ -64,11 +64,11 @@ function dateParse(input: string, formatString: string) {
return null return null
} }
export function dateParseFrontend(input: string) { export function dateParseFrontend(input: string): Date {
return dateParse(input, FRONTEND_FORMAT) return dateParse(input, FRONTEND_FORMAT)
} }
export function nowInTz(timezone = 'Europe/Berlin') { export function nowInTz(timezone = 'Europe/Berlin'): Date {
const now = new Date() const now = new Date()
return utcToZonedTime(now, timezone) return utcToZonedTime(now, timezone)
} }

View File

@@ -38,7 +38,7 @@ Buchungs-Link: ${getBaseURL()}/booking/${booking.uuid}
return value return value
} }
export function generateBookedCalendar(bookings: Booking[]) { export function generateBookedCalendar(bookings: Booking[]): string {
const events = bookings.map((booking) => ({ const events = bookings.map((booking) => ({
productId: 'app.vercel.pfadi-bussle/ics', productId: 'app.vercel.pfadi-bussle/ics',
calName: 'Pfadi-Bussle Buchungen', calName: 'Pfadi-Bussle Buchungen',

View File

@@ -31,7 +31,7 @@ Pfadi Bussle Wart
Tel. 0151/212 253 62 Tel. 0151/212 253 62
` `
function getReceivedBookingBookerText(booking: Booking) { function getReceivedBookingBookerText(booking: Booking): string {
return `Hallo liebe/r ${booking.booker.name}, return `Hallo liebe/r ${booking.booker.name},
Vielen Dank für Deine Buchungsanfrage zum ${daysFormatFrontend(booking.days)}! Vielen Dank für Deine Buchungsanfrage zum ${daysFormatFrontend(booking.days)}!
@@ -48,7 +48,7 @@ ${footer}
` `
} }
function getBookingConfirmedText(booking: Booking) { function getBookingConfirmedText(booking: Booking): string {
return `Hallo liebe/r ${booking.booker.name}, return `Hallo liebe/r ${booking.booker.name},
deine Buchunganfrage zum ${daysFormatFrontend( deine Buchunganfrage zum ${daysFormatFrontend(
@@ -64,7 +64,7 @@ einsehen und stornieren.
${footer} ${footer}
` `
} }
function getBookingRejectedText(booking: Booking) { function getBookingRejectedText(booking: Booking): string {
return `Hallo liebe/r ${booking.booker.name}, return `Hallo liebe/r ${booking.booker.name},
es tut uns leid aber deine Buchungsanfrage zum ${daysFormatFrontend( es tut uns leid aber deine Buchungsanfrage zum ${daysFormatFrontend(
@@ -78,7 +78,7 @@ ${footer}
` `
} }
function getReceivedBookingAdminText(booking: { uuid: string }) { function getReceivedBookingAdminText(booking: { uuid: string }): string {
return `Hallo lieber Admin, return `Hallo lieber Admin,
es ging folgende Buchung ein: ${getBaseURL()}/admin/booking/${booking.uuid} es ging folgende Buchung ein: ${getBaseURL()}/admin/booking/${booking.uuid}
@@ -86,7 +86,7 @@ es ging folgende Buchung ein: ${getBaseURL()}/admin/booking/${booking.uuid}
MfG` MfG`
} }
export async function sendReceivedBookingAdminMail(booking: Booking) { export async function sendReceivedBookingAdminMail(booking: Booking): Promise<void> {
try { try {
await sendMail({ await sendMail({
to: [{ email: ADMIN_EMAIL }], to: [{ email: ADMIN_EMAIL }],
@@ -102,7 +102,7 @@ export async function sendReceivedBookingAdminMail(booking: Booking) {
} }
} }
export async function sendReceivedBookingBookerMail(booking: Booking) { export async function sendReceivedBookingBookerMail(booking: Booking): Promise<void> {
try { try {
await sendMail({ await sendMail({
to: [{ email: booking.booker.email, name: booking.booker.name }], to: [{ email: booking.booker.email, name: booking.booker.name }],
@@ -118,7 +118,7 @@ export async function sendReceivedBookingBookerMail(booking: Booking) {
} }
} }
export async function sendBookingConfirmed(booking: Booking) { export async function sendBookingConfirmed(booking: Booking): Promise<void> {
try { try {
await sendMail({ await sendMail({
to: [{ email: booking.booker.email, name: booking.booker.name }], to: [{ email: booking.booker.email, name: booking.booker.name }],
@@ -143,7 +143,7 @@ export async function sendBookingConfirmed(booking: Booking) {
} }
} }
export async function sendBookingRejected(booking: Booking) { export async function sendBookingRejected(booking: Booking): Promise<void> {
try { try {
await sendMail({ await sendMail({
to: [{ email: booking.booker.email, name: booking.booker.name }], to: [{ email: booking.booker.email, name: booking.booker.name }],
@@ -175,7 +175,7 @@ async function sendMail({
type?: string type?: string
filename: string filename: string
}[] }[]
}) { }): Promise<void> {
const data = { const data = {
personalizations: [ personalizations: [
{ {

View File

@@ -6,7 +6,7 @@ export function authenticateAdmin({
}: { }: {
username: string username: string
password: string password: string
}) { }): boolean {
if (username !== 'admin') { if (username !== 'admin') {
return false return false
} }

View File

@@ -2,7 +2,7 @@ import { Bill } from '../../../../../db/bill'
import { createBill, patchBill } from '../../../../../db/index' import { createBill, patchBill } from '../../../../../db/index'
import withSession, { isAdminSession } from '../../../../../lib/session' import withSession, { isAdminSession } from '../../../../../lib/session'
export default withSession(async function billHandler(req, res) { export default withSession(async function billHandler(req, res): Promise<void> {
if (!isAdminSession(req)) { if (!isAdminSession(req)) {
res.status(403).send({ message: 'Not Authorized' }) res.status(403).send({ message: 'Not Authorized' })
return return

View File

@@ -7,7 +7,7 @@ import {
} from '../../../../../helpers/mail' } from '../../../../../helpers/mail'
import { BOOKING_STATUS } from '../../../../../db/enums' import { BOOKING_STATUS } from '../../../../../db/enums'
export default withSession(async function bookingHandler(req, res) { export default withSession(async function bookingHandler(req, res): Promise<void> {
if (!isAdminSession(req)) { if (!isAdminSession(req)) {
res.status(403).send({ message: 'Not Authorized' }) res.status(403).send({ message: 'Not Authorized' })
return return

View File

@@ -1,7 +1,7 @@
import { authenticateAdmin } from '../../../lib/authenticate' import { authenticateAdmin } from '../../../lib/authenticate'
import withSession from '../../../lib/session' import withSession from '../../../lib/session'
async function loginHandler(req: any, res: any) { async function loginHandler(req: any, res: any): Promise<void> {
const { method } = req const { method } = req
switch (method) { switch (method) {

View File

@@ -6,7 +6,7 @@ import { getBookingByUUID } from '../../../../db/index'
export default async function userHandler( export default async function userHandler(
req: NextApiRequest, req: NextApiRequest,
res: NextApiResponse res: NextApiResponse
) { ): Promise<void> {
const { const {
method, method,
query: { uuid: uuids }, query: { uuid: uuids },

View File

@@ -10,7 +10,7 @@ import {
export default async function userHandler( export default async function userHandler(
req: NextApiRequest, req: NextApiRequest,
res: NextApiResponse res: NextApiResponse
) { ): Promise<void> {
const { method } = req const { method } = req
let booking: Booking let booking: Booking

View File

@@ -5,7 +5,7 @@ import { generateBookedCalendar } from '../../helpers/ical'
export default async function useHandler( export default async function useHandler(
req: NextApiRequest, req: NextApiRequest,
res: NextApiResponse res: NextApiResponse
) { ): Promise<void> {
const { method } = req const { method } = req
switch (method) { switch (method) {

View File

@@ -4,7 +4,7 @@ import { getBookedDays } from '../../db/index'
export default async function useHandler( export default async function useHandler(
req: NextApiRequest, req: NextApiRequest,
res: NextApiResponse res: NextApiResponse
) { ): Promise<void> {
const { method } = req const { method } = req
switch (method) { switch (method) {