Skip to content

Commit

Permalink
refactor: use more optional chaining
Browse files Browse the repository at this point in the history
  • Loading branch information
mytlogos committed Aug 26, 2022
1 parent 1339934 commit 6cb63a4
Show file tree
Hide file tree
Showing 17 changed files with 27 additions and 27 deletions.
2 changes: 1 addition & 1 deletion packages/core/src/asyncStorage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
4 changes: 2 additions & 2 deletions packages/core/src/database/contexts/mediumContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ export class MediumContext extends SubContext {
* Adds a medium to the storage.
*/
public async addMedium(medium: SimpleMedium, uuid?: Uuid): Promise<SimpleMedium> {
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]);
Expand Down Expand Up @@ -652,7 +652,7 @@ export class MediumContext extends SubContext {
}

public async splitMedium(sourceMediumId: number, destMedium: SimpleMedium, toc: string): Promise<Id> {
if (!destMedium || !destMedium.medium || !destMedium.title) {
if (!destMedium?.medium || !destMedium.title) {
return Promise.reject(
new ValidationError(`Invalid destination Medium: ${destMedium?.title}-${destMedium?.medium}`),
);
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/database/contexts/mediumInWaitContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ export class MediumInWaitContext extends SubContext {
}

public async consumeMediaInWait(mediumId: number, same: MediumInWait[]): Promise<boolean> {
if (!same || !same.length) {
if (!same?.length) {
return false;
}
await Promise.all(
Expand Down
4 changes: 2 additions & 2 deletions packages/core/src/database/contexts/partContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 [];
}

Expand All @@ -159,7 +159,7 @@ export class PartContext extends SubContext {
*/
public async getParts<T extends MultiSingleNumber>(partId: T, uuid: Uuid, full = true): Promise<Part[]> {
const parts: Optional<any[]> = await this.queryInList("SELECT * FROM part WHERE id IN (??);", [partId]);
if (!parts || !parts.length) {
if (!parts?.length) {
return [];
}
const partIdMap = new Map<number, any>();
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/database/contexts/userContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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");
}

Expand Down
4 changes: 2 additions & 2 deletions packages/core/src/database/tableParser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand All @@ -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;
}
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/database/tableSchema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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})`;
Expand Down
6 changes: 3 additions & 3 deletions packages/scraper/src/externals/customv2/readability.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 || {};
Expand Down Expand Up @@ -1507,7 +1507,7 @@ export class Readability {
// Strip CDATA markers if present
const content = jsonLdElement.textContent?.replace(/^\s*<!\[CDATA\[|\]\]>\s*$/g, "") || "";
let parsed = JSON.parse(content);
if (!parsed["@context"] || !parsed["@context"].match(/^https?:\/\/schema\.org$/)) {
if (!parsed["@context"]?.match(/^https?:\/\/schema\.org$/)) {
return;
}

Expand All @@ -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;
}

Expand Down
2 changes: 1 addition & 1 deletion packages/scraper/src/externals/direct/directTools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<Node>;
let volumeEncountered = false;
for (const content of contents.iterate(ascending)) {
Expand Down
2 changes: 1 addition & 1 deletion packages/scraper/src/externals/direct/gogoAnimeScraper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,7 @@ async function scrapeToc(urlString: string): Promise<Toc[]> {

async function scrapeSearch(searchString: string, searchMedium: TocSearchMedium): Promise<TocSearchResult> {
const searchResults = await search(searchString);
if (!searchResults || !searchResults.length) {
if (!searchResults?.length) {
return { done: true };
}
for (const searchResult of searchResults) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
2 changes: 1 addition & 1 deletion packages/scraper/src/externals/direct/wuxiaworldScraper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -320,7 +320,7 @@ async function search(text: string): Promise<SearchResult[]> {

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) {
Expand Down
2 changes: 1 addition & 1 deletion packages/scraper/src/jobs/checkToc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ export const checkTocsJob = async (): Promise<JobRequest[]> => {
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),
Expand Down
6 changes: 3 additions & 3 deletions packages/scraper/src/jobs/news.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ export const scrapeNews = async (adapter: NewsScraper): Promise<NewsResult> => {
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(
Expand Down Expand Up @@ -84,7 +84,7 @@ async function processMediumNews(
): Promise<MediumInWait | undefined> {
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 };
}
Expand All @@ -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}'`);
}

Expand Down
2 changes: 1 addition & 1 deletion packages/scraper/src/scheduler/job.ts
Original file line number Diff line number Diff line change
Expand Up @@ -252,7 +252,7 @@ export class Job {
private async emit<E extends keyof Events>(event: E, ...args: Parameters<Events[E]>): Promise<boolean> {
const handler: EventListener[E] = this.events[event];

if (!handler || !handler.length) {
if (!handler?.length) {
return false;
}

Expand Down
8 changes: 4 additions & 4 deletions packages/scraper/src/scheduler/jobHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -242,7 +242,7 @@ function partEpisodesReleaseChanges(
storageEpisodes: Readonly<CombinedEpisode[]>,
storageReleases: Readonly<EpisodeRelease[]>,
): 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<
Expand Down Expand Up @@ -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);
}
}
Expand Down Expand Up @@ -529,7 +529,7 @@ export async function tocHandler(result: TocResult): EmptyPromise {
)} ${uuid || ""}`,
);

if (!tocs || !tocs.length) {
if (!tocs?.length) {
return;
}

Expand Down Expand Up @@ -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;
Expand Down
2 changes: 1 addition & 1 deletion packages/server/src/misc/fillSystemEvents.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down

0 comments on commit 6cb63a4

Please sign in to comment.