Skip to content

Commit

Permalink
chore: use conditional nullish operators
Browse files Browse the repository at this point in the history
  • Loading branch information
raymondfeng committed Jun 9, 2020
1 parent 4d329cf commit b307383
Show file tree
Hide file tree
Showing 30 changed files with 51 additions and 76 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ export class CasbinAuthorizationProvider implements Provider<Authorizer> {
const request: AuthorizationRequest = {
subject,
object,
action: (metadata.scopes && metadata.scopes[0]) || DEFAULT_SCOPE,
action: metadata.scopes?.[0] ?? DEFAULT_SCOPE,
};

const allowedRoles = metadata.allowedRoles;
Expand Down
2 changes: 1 addition & 1 deletion examples/greeter-extension/src/greeters/greeter-cn.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ export class ChineseGreeter implements Greeter {
) {}

greet(name: string) {
if (this.options && this.options.nameFirst === false) {
if (this.options?.nameFirst === false) {
return `你好,${name}!`;
}
return `${name},你好!`;
Expand Down
4 changes: 2 additions & 2 deletions examples/greeter-extension/src/greeting-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT

import {config, Getter, extensionPoint, extensions} from '@loopback/core';
import {config, extensionPoint, extensions, Getter} from '@loopback/core';
import chalk from 'chalk';
import {Greeter, GREETER_EXTENSION_POINT_NAME} from './types';

Expand Down Expand Up @@ -60,7 +60,7 @@ export class GreetingService {
// Fall back to English
greeting = `Hello, ${name}!`;
}
if (this.options && this.options.color) {
if (this.options?.color) {
greeting = chalk.keyword(this.options.color)(greeting);
}
return greeting;
Expand Down
2 changes: 1 addition & 1 deletion examples/hello-world/src/application.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export class HelloWorldApplication extends RestApplication {
async start() {
await super.start();

if (!(this.options && this.options.disableConsoleLog)) {
if (!this.options?.disableConsoleLog) {
const rest = await this.getServer(RestServer);
console.log(
`REST server running on port: ${await rest.get('rest.port')}`,
Expand Down
2 changes: 1 addition & 1 deletion examples/log-extension/src/mixins/log.mixin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export function LogMixin<T extends MixinTarget<Application>>(superClass: T) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
constructor(...args: any[]) {
super(...args);
if (this.options && this.options.logLevel) {
if (this.options?.logLevel) {
this.logLevel(this.options.logLevel);
}
this.component(LogComponent);
Expand Down
2 changes: 1 addition & 1 deletion examples/passport-login/src/sequence.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ export class MySequence implements SequenceHandler {
const args = await this.parseParams(request, route);

// if provider name is available in the request path params, set it in the query
if (route.pathParams && route.pathParams.provider) {
if (route.pathParams?.provider) {
request.query['oauth2-provider-name'] = route.pathParams.provider;
}

Expand Down
11 changes: 5 additions & 6 deletions examples/passport-login/src/services/user.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT

import {UserIdentityService} from '@loopback/authentication';
import {repository} from '@loopback/repository';
import {Profile as PassportProfile} from 'passport';
import {UserIdentityService} from '@loopback/authentication';
import {UserRepository} from '../repositories';
import {User} from '../models';
import {UserRepository} from '../repositories';
import {UserIdentityRepository} from '../repositories/user-identity.repository';

/**
Expand Down Expand Up @@ -43,10 +43,9 @@ export class PassportUserIdentityService
});
let user: User;
if (!users || !users.length) {
const name =
profile.name && profile.name.givenName
? profile.name.givenName + ' ' + profile.name.familyName
: profile.displayName;
const name = profile.name?.givenName
? profile.name.givenName + ' ' + profile.name.familyName
: profile.displayName;
user = await this.userRepository.create({
email: email,
name: name || JSON.stringify(profile.name),
Expand Down
8 changes: 3 additions & 5 deletions examples/rpc-server/src/rpc.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@
// License text available at https://opensource.org/licenses/MIT

import {
Context,
inject,
Application,
Context,
CoreBindings,
inject,
Server,
} from '@loopback/core';
import {once} from 'events';
Expand Down Expand Up @@ -35,9 +35,7 @@ export class RPCServer extends Context implements Server {
}

async start(): Promise<void> {
this._server = this.expressServer.listen(
(this.config && this.config.port) || 3000,
);
this._server = this.expressServer.listen(this.config?.port ?? 3000);
this._listening = true;
await once(this._server, 'listening');
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@
// Should it be imported from 'express'?
// The `Request` type from 'express' is not compatible
// with the one from `@loopback/rest` now.
import {UserProfile} from '@loopback/security';
import {Request} from '@loopback/rest';
import {UserProfile} from '@loopback/security';
import {AuthenticateOptions, Strategy} from 'passport';

/**
Expand Down Expand Up @@ -39,18 +39,10 @@ export class MockPassportStrategy extends Strategy {
* pass req.query.testState = 'error' to mock unexpected error
*/
async verify(request: Request) {
if (
request.headers &&
request.headers.testState &&
request.headers.testState === 'fail'
) {
if (request.headers?.testState === 'fail') {
this.returnUnauthorized('authorization failed');
return;
} else if (
request.headers &&
request.headers.testState &&
request.headers.testState === 'error'
) {
} else if (request.headers?.testState === 'error') {
this.returnError('unexpected error');
return;
}
Expand Down
14 changes: 4 additions & 10 deletions extensions/metrics/src/metrics.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,22 +31,16 @@ export class MetricsComponent implements Component {
@config()
options: MetricsOptions = DEFAULT_METRICS_OPTIONS,
) {
if (
!options.defaultMetrics ||
(options.defaultMetrics && !options.defaultMetrics.disabled)
) {
if (!options.defaultMetrics || !options.defaultMetrics?.disabled) {
this.application.lifeCycleObserver(MetricsObserver);
}
if (
!options.pushGateway ||
(options.pushGateway && !options.pushGateway.disabled)
) {
if (!options.pushGateway || !options.pushGateway?.disabled) {
this.application.lifeCycleObserver(MetricsPushObserver);
}
this.application.add(createBindingFromClass(MetricsInterceptor));
if (!options.endpoint || (options.endpoint && !options.endpoint.disabled)) {
if (!options.endpoint || !options.endpoint?.disabled) {
this.application.controller(
metricsControllerFactory(options.endpoint && options.endpoint.basePath),
metricsControllerFactory(options.endpoint?.basePath),
);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@
// License text available at https://opensource.org/licenses/MIT

import {
Application,
Context,
inject,
invokeMethod,
Provider,
Application,
} from '@loopback/core';
import {SecurityBindings, securityId, UserProfile} from '@loopback/security';
import {expect} from '@loopback/testlab';
Expand Down Expand Up @@ -151,7 +151,7 @@ describe('Authorization', () => {
const request: AuthorizationRequest = {
subject: authorizationCtx.principals[0].name,
object: metadata.resource ?? authorizationCtx.resource,
action: (metadata.scopes && metadata.scopes[0]) || 'execute',
action: metadata.scopes?.[0] ?? 'execute',
};
const allow = await this.enforcer.enforce(
request.subject,
Expand Down
12 changes: 4 additions & 8 deletions packages/boot/src/bootstrapper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@
// License text available at https://opensource.org/licenses/MIT

import {
Application,
Context,
CoreBindings,
inject,
resolveList,
Application,
CoreBindings,
} from '@loopback/core';
import debugModule from 'debug';
import {resolve} from 'path';
Expand Down Expand Up @@ -79,11 +79,7 @@ export class Bootstrapper {

// Determine the phases to be run. If a user set a phases filter, those
// are selected otherwise we run the default phases (BOOTER_PHASES).
const phases = execOptions
? execOptions.filter && execOptions.filter.phases
? execOptions.filter.phases
: BOOTER_PHASES
: BOOTER_PHASES;
const phases = execOptions?.filter?.phases ?? BOOTER_PHASES;

// Find booters registered to the BOOTERS_TAG by getting the bindings
const bindings = bootCtx.findByTag(BootTags.BOOTER);
Expand All @@ -100,7 +96,7 @@ export class Bootstrapper {
// names of booters that should be run), that is the value, otherwise it
// is all the registered booters by default.
const names = execOptions
? execOptions.filter && execOptions.filter.booters
? execOptions.filter?.booters
? execOptions.filter.booters
: defaultBooterNames
: defaultBooterNames;
Expand Down
2 changes: 1 addition & 1 deletion packages/context/src/binding-inspector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,7 @@ export function bindingTemplateFor<T>(
for (const t of templateFunctions) {
binding.apply(t);
}
if (spec && spec.target !== cls) {
if (spec?.target !== cls) {
// Remove name/key tags inherited from base classes
binding.apply(removeNameAndKeyTags);
}
Expand Down
2 changes: 1 addition & 1 deletion packages/context/src/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -502,7 +502,7 @@ export class Context extends EventEmitter {
if (filter(b)) bindings.push(b);
}

const parentBindings = this._parent && this._parent.find(filter);
const parentBindings = this._parent?.find(filter);
return this._mergeWithParent(bindings, parentBindings);
}

Expand Down
2 changes: 1 addition & 1 deletion packages/context/src/inject-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ export namespace config {
*/
function getCurrentBindingKey(session: ResolutionSession) {
// The current binding is not set if `instantiateClass` is invoked directly
return session.currentBinding && session.currentBinding.key;
return session.currentBinding?.key;
}

/**
Expand Down
2 changes: 1 addition & 1 deletion packages/express/src/express.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ export class ExpressServer extends BaseMiddlewareRegistry implements Server {
* will be 'http://localhost:3000' regardless of the `basePath`.
*/
get rootUrl(): string | undefined {
return this.httpServer && this.httpServer.url;
return this.httpServer?.url;
}

async start() {
Expand Down
4 changes: 2 additions & 2 deletions packages/http-server/src/http-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -152,15 +152,15 @@ export class HttpServer {
*/
public get port(): number {
if (typeof this._address === 'string') return 0;
return (this._address && this._address.port) || this.serverOptions.port!;
return this._address?.port || this.serverOptions.port!;
}

/**
* Host of the HTTP / HTTPS server
*/
public get host(): string | undefined {
if (typeof this._address === 'string') return undefined;
return (this._address && this._address.address) || this.serverOptions.host;
return this._address?.address || this.serverOptions.host;
}

/**
Expand Down
2 changes: 1 addition & 1 deletion packages/metadata/src/decorator-factory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ export class DecoratorFactory<
}

protected allowInheritance(): boolean {
return !!(this.options && this.options.allowInheritance);
return !!this.options?.allowInheritance;
}

/**
Expand Down
2 changes: 1 addition & 1 deletion packages/openapi-v3/src/build-responses-from-metadata.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ declare type ResponseMap = Map<

// eslint-disable-next-line @typescript-eslint/no-explicit-any
function isModel<T extends Model>(c: any): c is T {
return c && c.prototype instanceof Model;
return c?.prototype instanceof Model;
}

/**
Expand Down
2 changes: 1 addition & 1 deletion packages/openapi-v3/src/controller-spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,7 @@ function resolveControllerSpec(constructor: Function): ControllerSpec {
}

if (methodTags) {
if (operationSpec.tags && operationSpec.tags.length) {
if (operationSpec.tags?.length) {
operationSpec.tags = operationSpec.tags.concat(methodTags.tags);
} else {
operationSpec.tags = methodTags.tags;
Expand Down
3 changes: 1 addition & 2 deletions packages/openapi-v3/src/decorators/response.decorator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,7 @@ interface ResponseWithContent extends ResponseObject {
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function isResponseObject(c: any): c is ResponseWithContent {
// eslint-disable-next-line no-prototype-builtins
return !!c && c.hasOwnProperty('content') && !!c.content;
return !!c?.hasOwnProperty('content') && !!c.content;
}

function buildDecoratorReducer(
Expand Down
8 changes: 4 additions & 4 deletions packages/repository-json-schema/src/build-schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -342,12 +342,12 @@ function buildSchemaTitle<T extends object>(
function getTitleSuffix<T extends object>(options: JsonSchemaOptions<T> = {}) {
let suffix = '';

if (options.optional && options.optional.length) {
if (options.optional?.length) {
suffix += `Optional_${options.optional.join('-')}_`;
} else if (options.partial) {
suffix += 'Partial';
}
if (options.exclude && options.exclude.length) {
if (options.exclude?.length) {
suffix += `Excluding_${options.exclude.join('-')}_`;
}
if (options.includeRelations) {
Expand Down Expand Up @@ -463,7 +463,7 @@ export function modelToJsonSchema<T extends object>(
}

for (const p in meta.properties) {
if (options.exclude && options.exclude.includes(p as keyof T)) {
if (options.exclude?.includes(p as keyof T)) {
debug('Property % is excluded by %s', p, options.exclude);
continue;
}
Expand Down Expand Up @@ -562,7 +562,7 @@ export function modelToJsonSchema<T extends object>(
if (!schema || !Object.keys(schema).length) return;

// promote nested definition to the top level
if (result !== schema && schema.definitions) {
if (result !== schema?.definitions) {
for (const key in schema.definitions) {
if (key === title) continue;
result.definitions = result.definitions ?? {};
Expand Down
2 changes: 1 addition & 1 deletion packages/repository-tests/src/crud/transactions.suite.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ export function transactionSuite(
// reference of a `tx`.
// Detailed explanation see:
// https://github.com/strongloop/loopback-next/pull/4474
if (ds.connector && ds.connector.name === 'postgresql') {
if (ds.connector?.name === 'postgresql') {
tx = undefined;
}
if (tx?.isActive()) {
Expand Down
4 changes: 2 additions & 2 deletions packages/repository/src/model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,7 @@ function asObject(value: any, options?: Options): any {
*/
export abstract class Model {
static get modelName(): string {
return (this.definition && this.definition.name) || this.name;
return this.definition?.name || this.name;
}

static definition: ModelDefinition;
Expand Down Expand Up @@ -268,7 +268,7 @@ export abstract class Model {
const def = (this.constructor as typeof Model).definition;
const obj: AnyObject = {};

if (options && options.ignoreUnknownProperties === false) {
if (options?.ignoreUnknownProperties === false) {
const hiddenProperties: string[] = def?.settings.hiddenProperties || [];
for (const p in this) {
if (!hiddenProperties.includes(p)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,7 @@ export function resolveHasManyMetadata(
relationMeta = resolveHasManyMetaHelper(relationMeta);

const targetModel = relationMeta.target();
const targetModelProperties =
targetModel.definition && targetModel.definition.properties;
const targetModelProperties = targetModel.definition?.properties;

const sourceModel = relationMeta.source;

Expand Down
Loading

0 comments on commit b307383

Please sign in to comment.