From 6cb63a49223f1ea6f929d55c087caf1336e3ade2 Mon Sep 17 00:00:00 2001 From: mytlogos Date: Fri, 26 Aug 2022 17:43:03 +0200 Subject: [PATCH] refactor: use more optional chaining --- packages/core/src/asyncStorage.ts | 2 +- packages/core/src/database/contexts/mediumContext.ts | 4 ++-- .../core/src/database/contexts/mediumInWaitContext.ts | 2 +- packages/core/src/database/contexts/partContext.ts | 4 ++-- packages/core/src/database/contexts/userContext.ts | 2 +- packages/core/src/database/tableParser.ts | 4 ++-- packages/core/src/database/tableSchema.ts | 2 +- packages/scraper/src/externals/customv2/readability.ts | 6 +++--- packages/scraper/src/externals/direct/directTools.ts | 2 +- packages/scraper/src/externals/direct/gogoAnimeScraper.ts | 2 +- .../scraper/src/externals/direct/undergroundScraper.ts | 2 +- .../scraper/src/externals/direct/wuxiaworldScraper.ts | 2 +- packages/scraper/src/jobs/checkToc.ts | 2 +- packages/scraper/src/jobs/news.ts | 6 +++--- packages/scraper/src/scheduler/job.ts | 2 +- packages/scraper/src/scheduler/jobHandler.ts | 8 ++++---- packages/server/src/misc/fillSystemEvents.ts | 2 +- 17 files changed, 27 insertions(+), 27 deletions(-) diff --git a/packages/core/src/asyncStorage.ts b/packages/core/src/asyncStorage.ts index c26a625b..d71ba74b 100644 --- a/packages/core/src/asyncStorage.ts +++ b/packages/core/src/asyncStorage.ts @@ -24,7 +24,7 @@ createHook({ before() { const store: Store | any = localStorage.getStore(); - if (!store || !store.has) { + if (!(store instanceof Map)) { return; } const running = store.get(StoreKey.RUNNING); diff --git a/packages/core/src/database/contexts/mediumContext.ts b/packages/core/src/database/contexts/mediumContext.ts index a51d0bb6..9bab5c9b 100644 --- a/packages/core/src/database/contexts/mediumContext.ts +++ b/packages/core/src/database/contexts/mediumContext.ts @@ -50,7 +50,7 @@ export class MediumContext extends SubContext { * Adds a medium to the storage. */ public async addMedium(medium: SimpleMedium, uuid?: Uuid): Promise { - if (!medium || !medium.medium || !medium.title) { + if (!medium?.medium || !medium?.title) { return Promise.reject(new ValidationError(`Invalid Medium: ${medium?.title}-${medium?.medium}`)); } const result = await this.query("INSERT INTO medium(medium, title) VALUES (?,?);", [medium.medium, medium.title]); @@ -652,7 +652,7 @@ export class MediumContext extends SubContext { } public async splitMedium(sourceMediumId: number, destMedium: SimpleMedium, toc: string): Promise { - if (!destMedium || !destMedium.medium || !destMedium.title) { + if (!destMedium?.medium || !destMedium.title) { return Promise.reject( new ValidationError(`Invalid destination Medium: ${destMedium?.title}-${destMedium?.medium}`), ); diff --git a/packages/core/src/database/contexts/mediumInWaitContext.ts b/packages/core/src/database/contexts/mediumInWaitContext.ts index bd0aac7b..a2652abd 100644 --- a/packages/core/src/database/contexts/mediumInWaitContext.ts +++ b/packages/core/src/database/contexts/mediumInWaitContext.ts @@ -62,7 +62,7 @@ export class MediumInWaitContext extends SubContext { } public async consumeMediaInWait(mediumId: number, same: MediumInWait[]): Promise { - if (!same || !same.length) { + if (!same?.length) { return false; } await Promise.all( diff --git a/packages/core/src/database/contexts/partContext.ts b/packages/core/src/database/contexts/partContext.ts index d37e129e..7e158e27 100644 --- a/packages/core/src/database/contexts/partContext.ts +++ b/packages/core/src/database/contexts/partContext.ts @@ -132,7 +132,7 @@ export class PartContext extends SubContext { "SELECT * FROM part WHERE medium_id = ? AND combiIndex IN (??);", [mediumId, partCombiIndex], ); - if (!parts || !parts.length) { + if (!parts?.length) { return []; } @@ -159,7 +159,7 @@ export class PartContext extends SubContext { */ public async getParts(partId: T, uuid: Uuid, full = true): Promise { const parts: Optional = await this.queryInList("SELECT * FROM part WHERE id IN (??);", [partId]); - if (!parts || !parts.length) { + if (!parts?.length) { return []; } const partIdMap = new Map(); diff --git a/packages/core/src/database/contexts/userContext.ts b/packages/core/src/database/contexts/userContext.ts index bb38ba3a..ade7739c 100644 --- a/packages/core/src/database/contexts/userContext.ts +++ b/packages/core/src/database/contexts/userContext.ts @@ -169,7 +169,7 @@ export class UserContext extends SubContext { const sessionRecord = result[0]; - if (!sessionRecord || !sessionRecord.session_key) { + if (!sessionRecord?.session_key) { throw new SessionError("user has no session"); } diff --git a/packages/core/src/database/tableParser.ts b/packages/core/src/database/tableParser.ts index 9b94903b..199bf45f 100644 --- a/packages/core/src/database/tableParser.ts +++ b/packages/core/src/database/tableParser.ts @@ -238,7 +238,7 @@ export function parseDataColumn(table: TableSchema, _tables: TableSchema[], valu i++; const defaultValueObj = getExpressionValue(parts, i); - if (!defaultValueObj || !defaultValueObj.value) { + if (!defaultValueObj?.value) { logger.warn(`no default value specified for '${name}' of ${table.name}`); return null; } @@ -255,7 +255,7 @@ export function parseDataColumn(table: TableSchema, _tables: TableSchema[], valu i++; const updateValueObj = getExpressionValue(parts, i); - if (!updateValueObj || !updateValueObj.value) { + if (!updateValueObj?.value) { logger.warn(`no update value specified for '${name}' of ${table.name}`); return null; } diff --git a/packages/core/src/database/tableSchema.ts b/packages/core/src/database/tableSchema.ts index a41a1b98..18873256 100644 --- a/packages/core/src/database/tableSchema.ts +++ b/packages/core/src/database/tableSchema.ts @@ -44,7 +44,7 @@ export class TableSchema { if (!foreignKey) { throw new SchemaError("invalid foreign key: is undefined"); } - if (!foreignKey.table || !foreignKey.table.name) { + if (!foreignKey.table?.name) { throw new SchemaError("invalid foreign key: empty table"); } return `FOREIGN KEY (${value.name}) REFERENCES ${foreignKey.table.name}(${foreignKey.name})`; diff --git a/packages/scraper/src/externals/customv2/readability.ts b/packages/scraper/src/externals/customv2/readability.ts index e9bcc3cb..8c65b278 100644 --- a/packages/scraper/src/externals/customv2/readability.ts +++ b/packages/scraper/src/externals/customv2/readability.ts @@ -213,7 +213,7 @@ export class Readability { private _articleLang?: string | null; public constructor(doc: Document, options?: ReadabilityOptions) { - if (!doc || !doc.documentElement) { + if (!doc?.documentElement) { throw new Error("First argument to Readability constructor should be a document object."); } options = options || {}; @@ -1507,7 +1507,7 @@ export class Readability { // Strip CDATA markers if present const content = jsonLdElement.textContent?.replace(/^\s*\s*$/g, "") || ""; let parsed = JSON.parse(content); - if (!parsed["@context"] || !parsed["@context"].match(/^https?:\/\/schema\.org$/)) { + if (!parsed["@context"]?.match(/^https?:\/\/schema\.org$/)) { return; } @@ -1517,7 +1517,7 @@ export class Readability { }); } - if (!parsed || !parsed["@type"] || !parsed["@type"].match(this.REGEXPS.jsonLdArticleTypes)) { + if (!parsed?.["@type"]?.match(this.REGEXPS.jsonLdArticleTypes)) { return; } diff --git a/packages/scraper/src/externals/direct/directTools.ts b/packages/scraper/src/externals/direct/directTools.ts index 0284cfbf..5c3cf5a9 100644 --- a/packages/scraper/src/externals/direct/directTools.ts +++ b/packages/scraper/src/externals/direct/directTools.ts @@ -777,7 +777,7 @@ function adjustTocContentsLinked(contents: TocLinkedList, state: TocScrapeState) insertNeighbour = episode; } } - if (!state.tocMeta || !state.tocMeta.end) { + if (!state.tocMeta?.end) { let possibleStartNode: Optional; let volumeEncountered = false; for (const content of contents.iterate(ascending)) { diff --git a/packages/scraper/src/externals/direct/gogoAnimeScraper.ts b/packages/scraper/src/externals/direct/gogoAnimeScraper.ts index d62ed9c1..2f2b4b0a 100644 --- a/packages/scraper/src/externals/direct/gogoAnimeScraper.ts +++ b/packages/scraper/src/externals/direct/gogoAnimeScraper.ts @@ -172,7 +172,7 @@ async function scrapeToc(urlString: string): Promise { async function scrapeSearch(searchString: string, searchMedium: TocSearchMedium): Promise { const searchResults = await search(searchString); - if (!searchResults || !searchResults.length) { + if (!searchResults?.length) { return { done: true }; } for (const searchResult of searchResults) { diff --git a/packages/scraper/src/externals/direct/undergroundScraper.ts b/packages/scraper/src/externals/direct/undergroundScraper.ts index d8684de2..e7627498 100644 --- a/packages/scraper/src/externals/direct/undergroundScraper.ts +++ b/packages/scraper/src/externals/direct/undergroundScraper.ts @@ -98,7 +98,7 @@ async function processMediumNews(mediumTitle: string, potentialNews: News[]): Em type: MediaType.TEXT, }); - if (!likeMedium || !likeMedium.medium || !likeMedium.medium.id) { + if (!likeMedium?.medium?.id) { return; } const mediumId = likeMedium.medium.id; diff --git a/packages/scraper/src/externals/direct/wuxiaworldScraper.ts b/packages/scraper/src/externals/direct/wuxiaworldScraper.ts index 6d8979e9..a05378c0 100644 --- a/packages/scraper/src/externals/direct/wuxiaworldScraper.ts +++ b/packages/scraper/src/externals/direct/wuxiaworldScraper.ts @@ -320,7 +320,7 @@ async function search(text: string): Promise { const searchResult: SearchResult[] = []; - if (!parsed.result || !parsed.items || !parsed.items.length) { + if (!parsed.result || !parsed.items?.length) { return searchResult; } for (const item of parsed.items) { diff --git a/packages/scraper/src/jobs/checkToc.ts b/packages/scraper/src/jobs/checkToc.ts index 8c767991..ad79e5e1 100644 --- a/packages/scraper/src/jobs/checkToc.ts +++ b/packages/scraper/src/jobs/checkToc.ts @@ -58,7 +58,7 @@ export const checkTocsJob = async (): Promise => { mediumTocs, ); } - if (mediumTocs.some((mediumToc) => hooks.every((hook) => !hook.domainReg || !hook.domainReg.test(mediumToc)))) { + if (mediumTocs.some((mediumToc) => hooks.every((hook) => !hook.domainReg?.test(mediumToc)))) { return searchTocJob( mediumId, tocSearchMedia.find((searchMedium) => searchMedium.mediumId === mediumId), diff --git a/packages/scraper/src/jobs/news.ts b/packages/scraper/src/jobs/news.ts index 1a5464e9..86aa95d8 100644 --- a/packages/scraper/src/jobs/news.ts +++ b/packages/scraper/src/jobs/news.ts @@ -51,7 +51,7 @@ export const scrapeNews = async (adapter: NewsScraper): Promise => { const promises = []; for (const value of episodeMap.values()) { const [newsItem] = value; - if (!newsItem || !newsItem.mediumTitle || !newsItem.mediumType) { + if (!newsItem?.mediumTitle || !newsItem.mediumType) { continue; } promises.push( @@ -84,7 +84,7 @@ async function processMediumNews( ): Promise { const likeMedium: LikeMedium = await mediumStorage.getLikeMedium({ title, type }); - if (!likeMedium || !likeMedium.medium || !likeMedium.medium.id) { + if (!likeMedium?.medium?.id) { if (tocLink) { return { title, medium: type, link: tocLink }; } @@ -103,7 +103,7 @@ async function processMediumNews( let standardPart = await partStorage.getStandardPart(mediumId); standardPart ??= await partStorage.createStandardPart(mediumId); - if (!standardPart || !standardPart.id) { + if (!standardPart?.id) { throw new DatabaseError(`could not create standard part for mediumId: '${mediumId}'`); } diff --git a/packages/scraper/src/scheduler/job.ts b/packages/scraper/src/scheduler/job.ts index f6766904..fd8b903b 100644 --- a/packages/scraper/src/scheduler/job.ts +++ b/packages/scraper/src/scheduler/job.ts @@ -252,7 +252,7 @@ export class Job { private async emit(event: E, ...args: Parameters): Promise { const handler: EventListener[E] = this.events[event]; - if (!handler || !handler.length) { + if (!handler?.length) { return false; } diff --git a/packages/scraper/src/scheduler/jobHandler.ts b/packages/scraper/src/scheduler/jobHandler.ts index 1aacb769..34d016be 100644 --- a/packages/scraper/src/scheduler/jobHandler.ts +++ b/packages/scraper/src/scheduler/jobHandler.ts @@ -242,7 +242,7 @@ function partEpisodesReleaseChanges( storageEpisodes: Readonly, storageReleases: Readonly, ): PartChanges { - if (!value.part || !value.part.id) { + if (!value.part?.id) { throw new ValidationError(`something went wrong. got no part for tocPart ${value.tocPart.combiIndex}`); } const episodeMap = new Map< @@ -400,7 +400,7 @@ function filterToDeleteReleases(tocId: number, changes: PartChanges, releases: E // to delete the release either the episode of it should not be defined or the release // (same url only, as same episodeId and tocId is already given) should not be available - if (!tocReleases || !tocReleases.find((other) => other.url === release.url)) { + if (!tocReleases?.find((other) => other.url === release.url)) { deleteReleases.push(release); } } @@ -529,7 +529,7 @@ export async function tocHandler(result: TocResult): EmptyPromise { )} ${uuid || ""}`, ); - if (!tocs || !tocs.length) { + if (!tocs?.length) { return; } @@ -825,7 +825,7 @@ async function listHandler(result: ExternalListResult): EmptyPromise { const likeMedium = likeMedia.find((like: LikeMedium) => { return like && like.link === scrapeMedium.title.link; }); - if (!likeMedium || !likeMedium.medium) { + if (!likeMedium?.medium) { throw new MissingEntityError("missing medium in storage for " + scrapeMedium.title.link); } return likeMedium.medium.id; diff --git a/packages/server/src/misc/fillSystemEvents.ts b/packages/server/src/misc/fillSystemEvents.ts index 2cbce5b1..7c7a1144 100644 --- a/packages/server/src/misc/fillSystemEvents.ts +++ b/packages/server/src/misc/fillSystemEvents.ts @@ -103,7 +103,7 @@ async function streamed() { const maxDiff = 1000 * 3600; // at most a hour difference jobs.on("result", (value) => { - if (!value.start || !value.start.getTime) { + if (!value.start?.getTime) { console.log(value); return; }