Skip to content

Commit cfd29b4

Browse files
committed
fix strictNullChecks errors in source files
Fix ~240 null-safety issues across providers, business, routes, middleware, lib, and bin.
1 parent e86844a commit cfd29b4

43 files changed

Lines changed: 268 additions & 259 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

bin/config.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -191,10 +191,10 @@ export default {
191191
website: config.get('WEBSITE_ENDPOINT') || 'http://localhost:3000'
192192
},
193193
limits: {
194-
windowSeconds: Number.parseInt(config.get('RATE_LIMIT_WINDOW'), 10) || 1,
195-
max: Number.parseInt(config.get('RATE_LIMIT_MAX'), 10) || 0,
196-
batchWindowSeconds: Number.parseInt(config.get('BATCH_RATE_LIMIT_WINDOW'), 10) || 1,
197-
batchMax: Number.parseInt(config.get('BATCH_RATE_LIMIT_MAX'), 10) || 0
194+
windowSeconds: Number.parseInt(config.get('RATE_LIMIT_WINDOW')!, 10) || 1,
195+
max: Number.parseInt(config.get('RATE_LIMIT_MAX')!, 10) || 0,
196+
batchWindowSeconds: Number.parseInt(config.get('BATCH_RATE_LIMIT_WINDOW')!, 10) || 1,
197+
batchMax: Number.parseInt(config.get('BATCH_RATE_LIMIT_MAX')!, 10) || 0
198198
},
199199
webhook: {
200200
githubSecret:

business/definitionService.ts

Lines changed: 17 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -321,7 +321,7 @@ export class DefinitionService {
321321
} else {
322322
result = await this.recomputeHandler.compute(this, coordinates)
323323
}
324-
return this._trimDefinition(this._cast(result), expand)
324+
return this._trimDefinition(this._cast(result!), expand)
325325
}
326326

327327
/** Get directly from cache or store without any side effect, like compute */
@@ -389,7 +389,7 @@ export class DefinitionService {
389389
}
390390

391391
_cast(definition: Definition): Definition {
392-
definition.coordinates = EntityCoordinates.fromObject(definition.coordinates)
392+
definition.coordinates = EntityCoordinates.fromObject(definition.coordinates)!
393393
return definition
394394
}
395395

@@ -428,7 +428,7 @@ export class DefinitionService {
428428
}
429429
const curated = (await this.curationService.list(coordinates)).map(c => c.toString())
430430
const tools = await this.harvestStore.list(coordinates)
431-
const harvest = tools.map(tool => EntityCoordinates.fromString(tool).toString())
431+
const harvest = tools.map(tool => EntityCoordinates.fromString(tool)!.toString())
432432
return sortedUniq([...harvest, ...curated])
433433
}
434434

@@ -452,12 +452,12 @@ export class DefinitionService {
452452
}
453453
})
454454
)
455-
const foundDefinitions = flatten(await Promise.all(concat(promises)))
455+
const foundDefinitions = flatten(await Promise.all(concat(promises))).filter((x): x is string => x !== null)
456456
// Filter only the revisions matching the found definitions
457457
return intersectionWith(
458458
coordinatesList,
459459
foundDefinitions,
460-
(a, b) => a && b && a.toString().toLowerCase() === b.toString().toLowerCase()
460+
(a, b) => a.toString().toLowerCase() === b.toString().toLowerCase()
461461
)
462462
}
463463

@@ -695,7 +695,7 @@ export class DefinitionService {
695695
for (const version in raw[tool]) {
696696
const cased = get(raw[tool][version], '_metadata.links.self.href')
697697
if (cased) {
698-
return EntityCoordinates.fromUrn(cased)
698+
return EntityCoordinates.fromUrn(cased)!
699699
}
700700
}
701701
}
@@ -736,8 +736,8 @@ export class DefinitionService {
736736

737737
_ensureFinalScores(definition: Definition): void {
738738
const { described, licensed } = definition
739-
set(definition, 'scores.effective', Math.floor((described.score.total + licensed.score.total) / 2))
740-
set(definition, 'scores.tool', Math.floor((described.toolScore.total + licensed.toolScore.total) / 2))
739+
set(definition, 'scores.effective', Math.floor((described!.score!.total + licensed!.score!.total) / 2))
740+
set(definition, 'scores.tool', Math.floor((described!.toolScore!.total + licensed!.toolScore!.total) / 2))
741741
}
742742

743743
_finalizeDefinition(coordinates: EntityCoordinates, definition: Definition): void {
@@ -847,7 +847,7 @@ export class DefinitionService {
847847

848848
_collectLicenseTexts(definition: Definition): string[] {
849849
const result: Set<string> = new Set()
850-
for (const file of definition.files.filter(DefinitionService._isLicenseFile)) {
850+
for (const file of definition.files!.filter(DefinitionService._isLicenseFile)) {
851851
this._extractLicensesFromExpression(file.license, result)
852852
}
853853
return Array.from(result)
@@ -872,7 +872,7 @@ export class DefinitionService {
872872

873873
/** Answer whether or not the given file is a license text file */
874874
static _isLicenseFile(file: DefinitionFile): boolean {
875-
return file.token && DefinitionService._isInCoreFacet(file) && (file.natures || []).includes('license')
875+
return !!file.token && DefinitionService._isInCoreFacet(file) && (file.natures || []).includes('license')
876876
}
877877

878878
/** Suggest a set of definition coordinates that match the given pattern. Only existing definitions are searched. */
@@ -884,20 +884,20 @@ export class DefinitionService {
884884
* Helper method to prime the search store while getting the system up and running.
885885
* Should not be needed in general.
886886
*/
887-
async reload(mode: string, coordinatesList: string[] | null = null): Promise<(undefined | null)[]> {
887+
async reload(mode: string, coordinatesList: string[] | null = null): Promise<(void | null | undefined)[]> {
888888
const recompute = mode === 'definitions'
889889
const baseList = coordinatesList || (await this.list(new EntityCoordinates(), recompute))
890-
const list = baseList.map(entry => EntityCoordinates.fromString(entry))
890+
const list = baseList.map(entry => EntityCoordinates.fromString(entry)!)
891891
return await Promise.all(
892892
list.map(
893893
throat(10, async (coordinates: EntityCoordinates) => {
894894
try {
895895
const definition = await this.get(coordinates, null, recompute)
896896
if (recompute) {
897-
return Promise.resolve(null)
897+
return null
898898
}
899899
if (this.search.store) {
900-
return this.search.store(definition)
900+
return this.search.store(definition!)
901901
}
902902
} catch (error) {
903903
this.logger.info('failed to reload in definition service', {
@@ -984,7 +984,7 @@ export class DefinitionService {
984984

985985
_ensureSourceLocation(coordinates: EntityCoordinates, definition: Definition): void {
986986
if (get(definition, 'described.sourceLocation')) {
987-
updateSourceLocation(definition.described.sourceLocation)
987+
updateSourceLocation(definition.described!.sourceLocation!)
988988
return
989989
}
990990
// For source components there may not be an explicit harvested source location (it is self-evident)
@@ -999,7 +999,7 @@ export class DefinitionService {
999999
return
10001000
}
10011001
this._ensureDescribed(definition)
1002-
definition.described.sourceLocation = { ...coordinates, url }
1002+
definition.described!.sourceLocation = { ...coordinates, url }
10031003
break
10041004
}
10051005
default:
@@ -1025,7 +1025,7 @@ export class DefinitionService {
10251025
}
10261026

10271027
_getCacheKey(coordinates: EntityCoordinates): string {
1028-
return `def_${EntityCoordinates.fromObject(coordinates).toString().toLowerCase()}`
1028+
return `def_${EntityCoordinates.fromObject(coordinates)!.toString().toLowerCase()}`
10291029
}
10301030
}
10311031

business/suggestionService.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,7 @@ export class SuggestionService {
8787
*/
8888
async _getRelatedDefinitions(coordinates: EntityCoordinates): Promise<RelatedDefinitions | null> {
8989
const query = coordinates.asRevisionless()
90-
query.namespace = query.namespace ? query.namespace : null // explicitly exclude namespace
90+
query.namespace = query.namespace ? query.namespace : (null as unknown as string) // explicitly exclude namespace
9191
const results = await this.definitionService.find(query)
9292
const definitions = results.data.sort((a, b) =>
9393
compareDates(get(a, 'described.releaseDate'), get(b, 'described.releaseDate'))

lib/licenseMatcher.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -119,8 +119,8 @@ class DefinitionLicenseMatchPolicy implements LicenseMatchPolicy {
119119
const sourceLicenseFiles = this._getLicenseFile(source.definition)
120120
const targetLicenseFiles = this._getLicenseFile(target.definition)
121121
const fileMap = new Map()
122-
this._addFileToMap(fileMap, sourceLicenseFiles, 'sourceFile')
123-
this._addFileToMap(fileMap, targetLicenseFiles, 'targetFile')
122+
this._addFileToMap(fileMap, sourceLicenseFiles || [], 'sourceFile')
123+
this._addFileToMap(fileMap, targetLicenseFiles || [], 'targetFile')
124124
return fileMap
125125
}
126126

@@ -196,7 +196,7 @@ class HarvestLicenseMatchPolicy implements LicenseMatchPolicy {
196196
* Compare harvest license data between source and target
197197
*/
198198
compare(source: LicenseMatchInput, target: LicenseMatchInput): CompareResult {
199-
const type = source.definition.coordinates.type
199+
const type = source.definition.coordinates!.type!
200200
const strategy = this._getStrategy(type)
201201
return strategy.compare(source, target)
202202
}
@@ -324,7 +324,7 @@ function getLatestToolHarvest(coordinateHarvest: CoordinateHarvest, tool: string
324324
return undefined
325325
}
326326
const latestVersion = getLatestVersion(Object.keys(coordinateHarvest[tool]))
327-
return get(coordinateHarvest, [tool, latestVersion]) as object | undefined
327+
return get(coordinateHarvest, [tool, latestVersion!]) as object | undefined
328328
}
329329

330330
export { DefinitionLicenseMatchPolicy, HarvestLicenseMatchPolicy, LicenseMatcher }

middleware/github.ts

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -73,29 +73,29 @@ const middleware: RequestHandler = asyncMiddleware(async (req, res, next) => {
7373
return
7474
}
7575

76-
const serviceToken = options.token
76+
const serviceToken = options!.token
7777
const serviceClient = await setupServiceClient(req, serviceToken)
7878
const userToken = authHeader ? authHeader.split(' ')[1] : null
7979
const userClient = await setupUserClient(req, userToken)
8080

8181
req.app.locals.user.github.getInfo = async () => {
8282
if (!req.app.locals.user.github._info) {
8383
const infoCacheKey = userClient
84-
? await getCacheKey('github.user', userToken)
84+
? await getCacheKey('github.user', userToken!)
8585
: await getCacheKey('github.user', serviceToken)
8686
await setupInfo(req, infoCacheKey, userClient || serviceClient)
8787
}
8888

89-
return req.app.locals.user.github._info
89+
return req.app.locals.user.github._info!
9090
}
9191

92-
req.app.locals.user.github.getTeams = async () => {
92+
req.app.locals.user.github.getTeams = async (): Promise<string[]> => {
9393
if (!req.app.locals.user.github._teams) {
94-
const teamCacheKey = userClient ? await getCacheKey('github.team', userToken) : null
94+
const teamCacheKey = userClient ? await getCacheKey('github.team', userToken!) : null
9595
await setupTeams(req, teamCacheKey, userClient)
9696
}
9797

98-
return req.app.locals.user.github._teams
98+
return req.app.locals.user.github._teams!
9999
}
100100

101101
next()
@@ -128,11 +128,11 @@ async function setupUserClient(req: Request, token: string | null): Promise<Octo
128128

129129
// Get GitHub user info and attach it to the request
130130
async function setupInfo(req: Request, cacheKey: string, client: Octokit): Promise<void> {
131-
let info = await cache.get(cacheKey)
131+
let info = await cache!.get(cacheKey)
132132
if (!info) {
133133
info = await client.rest.users.getAuthenticated()
134134
info = { name: info.data.name, login: info.data.login, email: info.data.email }
135-
await cache.set(cacheKey, info)
135+
await cache!.set(cacheKey, info)
136136
}
137137
req.app.locals.user.github._info = info
138138
}
@@ -144,10 +144,10 @@ async function setupTeams(req: Request, cacheKey: string | null, client: Octokit
144144
return
145145
}
146146
// check cache for team data; hash the token so we're not storing them raw
147-
let teams = await cache.get(cacheKey)
147+
let teams = await cache!.get(cacheKey)
148148
if (!teams) {
149-
teams = await getTeams(client, options.org)
150-
await cache.set(cacheKey, teams)
149+
teams = await getTeams(client, options!.org)
150+
await cache!.set(cacheKey, teams)
151151
}
152152
req.app.locals.user.github._teams = teams
153153
}

middleware/githubConfig.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,11 +25,11 @@ export interface GitHubConfigOptions extends GitHubMiddlewareOptions {
2525
const defaultOptions: GitHubConfigOptions = {
2626
clientId: config.get('AUTH_GITHUB_CLIENT_ID'),
2727
clientSecret: config.get('AUTH_GITHUB_CLIENT_SECRET'),
28-
token: config.get('CURATION_GITHUB_TOKEN'),
28+
token: config.get('CURATION_GITHUB_TOKEN')!,
2929
org: config.get('AUTH_GITHUB_ORG') || 'clearlydefined',
3030
permissions: {
3131
harvest: [config.get('AUTH_HARVEST_TEAM') || 'harvest-dev'],
32-
curate: [config.get('AUTH_CURATION_TEAM'), 'curation-dev']
32+
curate: [config.get('AUTH_CURATION_TEAM')!, 'curation-dev']
3333
}
3434
}
3535
const defaultCache = memoryCache({ defaultTtlSeconds: 10 * 60 /* 10 mins */ })

providers/caching/redisConfig.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,9 @@ import redis from './redis.ts'
1111
* allowing for custom configuration when needed.
1212
*/
1313
function serviceFactory(options?: RedisCacheOptions): RedisCache {
14-
const realOptions = options || {
15-
service: config.get('CACHING_REDIS_SERVICE'),
16-
apiKey: config.get('CACHING_REDIS_API_KEY'),
14+
const realOptions: RedisCacheOptions = options || {
15+
service: config.get('CACHING_REDIS_SERVICE')!,
16+
apiKey: config.get('CACHING_REDIS_API_KEY')!,
1717
port: Number(config.get('CACHING_REDIS_PORT')) || 6380
1818
}
1919
return redis(realOptions)

providers/curation/azureQueueConfig.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,8 @@ import type { AzureStorageQueueOptions } from '../queueing/azureStorageQueue.ts'
66
import AzureStorageQueue from '../queueing/azureStorageQueue.ts'
77

88
function azure(options?: AzureStorageQueueOptions): AzureStorageQueue {
9-
const realOptions = options || {
10-
connectionString: config.get('CURATION_QUEUE_CONNECTION_STRING') || config.get('HARVEST_AZBLOB_CONNECTION_STRING'),
9+
const realOptions: AzureStorageQueueOptions = options || {
10+
connectionString: (config.get('CURATION_QUEUE_CONNECTION_STRING') || config.get('HARVEST_AZBLOB_CONNECTION_STRING'))!,
1111
queueName: config.get('CURATION_QUEUE_NAME') || 'curations'
1212
}
1313
return new AzureStorageQueue(realOptions)

0 commit comments

Comments
 (0)