[🔧 ESLint] several different rules fixes (#737)

This commit is contained in:
Dimitri POSTOLOV 2022-12-28 21:38:03 +01:00 committed by GitHub
parent 02469da474
commit bd5496ebff
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
41 changed files with 128 additions and 121 deletions

View file

@ -9,6 +9,14 @@ const rulesToExtends = Object.fromEntries(
'import/first',
'no-restricted-globals',
'@typescript-eslint/no-unused-vars',
'unicorn/no-useless-fallback-in-spread',
'unicorn/no-array-push-push',
'no-else-return',
'no-lonely-if',
'unicorn/prefer-includes',
'react/self-closing-comp',
'prefer-const',
'no-extra-boolean-cast',
].includes(key),
),
);

View file

@ -57,7 +57,7 @@ export function deployClickhouse() {
protocol: 'http',
host: serviceLocalHost(chApi.service),
port: String(chApi.port),
password: password,
password,
username,
cloud: null,
};

View file

@ -83,7 +83,7 @@ export function deployUsageIngestor({
cpuAverageToScale: 60,
limit: cpuLimit,
},
maxReplicas: maxReplicas,
maxReplicas,
},
},
[

View file

@ -69,7 +69,7 @@ export function deployUsage({
cpuAverageToScale: 60,
limit: cpuLimit,
},
maxReplicas: maxReplicas,
maxReplicas,
},
},
[

View file

@ -27,7 +27,7 @@ export class PodBuilder extends kx.PodBuilder {
selector: { matchLabels: appLabels },
replicas: _args.replicas ?? 1,
template: {
metadata: { labels: appLabels, ...(metadata || {}) },
metadata: { labels: appLabels, ...metadata },
spec: this.podSpec,
},
};

View file

@ -84,8 +84,10 @@ export class ServiceDeployment {
}
if (this.options.exposesMetrics) {
additionalEnv.push({ name: 'METRICS_ENABLED', value: 'true' }); // TODO: remove this
additionalEnv.push({ name: 'PROMETHEUS_METRICS', value: '1' });
additionalEnv.push(
{ name: 'METRICS_ENABLED', value: 'true' }, // TODO: remove this
{ name: 'PROMETHEUS_METRICS', value: '1' },
);
}
const pb = new PodBuilder({

View file

@ -673,7 +673,7 @@ describe('update', () => {
document: UpdateOIDCIntegrationMutation,
variables: {
input: {
oidcIntegrationId: oidcIntegrationId,
oidcIntegrationId,
clientId: 'bbbb',
clientSecret: 'bbbbbbbbbbbb',
tokenEndpoint: 'http://localhost:8888/bbbb/token',

View file

@ -117,7 +117,7 @@ export function hiveApollo(clientOrOptions: HiveClient | HivePluginOptions): Apo
...clientOrOptions,
agent: {
name: 'hive-client-apollo',
...(clientOrOptions.agent ?? {}),
...clientOrOptions.agent,
},
});

View file

@ -12,7 +12,7 @@ export function useHive(clientOrOptions: HiveClient | HivePluginOptions): Plugin
...clientOrOptions,
agent: {
name: 'hive-client-envelop',
...(clientOrOptions.agent ?? {}),
...clientOrOptions.agent,
},
});

View file

@ -44,12 +44,12 @@ export function createReporting(pluginOptions: HivePluginOptions): SchemaReporte
const agent = createAgent<GraphQLSchema, ExecutionResult<SchemaPublishMutation>>(
{
logger,
...(pluginOptions.agent ?? {}),
...pluginOptions.agent,
endpoint:
selfHostingOptions?.graphqlEndpoint ??
reportingOptions.endpoint ??
'https://app.graphql-hive.com/graphql',
token: token,
token,
enabled: pluginOptions.enabled,
debug: pluginOptions.debug,
},

View file

@ -293,11 +293,10 @@ export function createCollector({
if (collected_entire_named_types.has(namedType.name)) {
// No need to mark this type as used again
return;
} else {
// Add this type to the set of types that have been marked as used
// to avoid infinite loops
collected_entire_named_types.add(namedType.name);
}
// Add this type to the set of types that have been marked as used
// to avoid infinite loops
collected_entire_named_types.add(namedType.name);
if (isScalarType(namedType)) {
markAsUsed(makeId(namedType.name));

View file

@ -481,7 +481,7 @@ test('should display SchemaPublishMissingServiceError', async () => {
maxRetries: 1,
logger,
},
token: token,
token,
reporting: {
author: 'Test',
commit: 'Commit',
@ -543,7 +543,7 @@ test('should display SchemaPublishMissingUrlError', async () => {
maxRetries: 1,
logger,
},
token: token,
token,
reporting: {
author: 'Test',
commit: 'Commit',

View file

@ -83,23 +83,21 @@ export class AuthManager {
token: this.apiToken,
});
}
} else if (hasManyTargets(selector)) {
await Promise.all(
selector.target.map(target =>
this.ensureTargetAccess({
...selector,
target,
}),
),
);
} else {
if (hasManyTargets(selector)) {
await Promise.all(
selector.target.map(target =>
this.ensureTargetAccess({
...selector,
target,
}),
),
);
} else {
const user = await this.getCurrentUser();
await this.targetAccess.ensureAccessForUser({
...(selector as TargetAccessSelector),
user: user.id,
});
}
const user = await this.getCurrentUser();
await this.targetAccess.ensureAccessForUser({
...(selector as TargetAccessSelector),
user: user.id,
});
}
}

View file

@ -36,7 +36,8 @@ export class CdnProvider {
getCdnUrlForTarget(targetId: string): string {
if (this.config.providers.cloudflare) {
return `${this.config.providers.cloudflare.baseUrl}/artifacts/v1/${targetId}`;
} else if (this.config.providers.api) {
}
if (this.config.providers.api) {
return `${this.config.providers.api.baseUrl}/artifacts/v1/${targetId}`;
}

View file

@ -17,8 +17,8 @@ export const resolvers: LabModule.Resolvers = {
]);
await injector.get(AuthManager).ensureTargetAccess({
organization: organization,
project: project,
organization,
project,
target,
scope: TargetAccessScope.REGISTRY_READ,
});

View file

@ -250,7 +250,7 @@ export class OperationsReader {
})}
GROUP BY coordinate
`,
queryId: queryId,
queryId,
timeout: 30_000,
span,
});
@ -1638,8 +1638,10 @@ export class OperationsReader {
}
if (period) {
where.push(`timestamp >= toDateTime('${formatDate(period.from)}', 'UTC')`);
where.push(`timestamp <= toDateTime('${formatDate(period.to)}', 'UTC')`);
where.push(
`timestamp >= toDateTime('${formatDate(period.from)}', 'UTC')`,
`timestamp <= toDateTime('${formatDate(period.to)}', 'UTC')`,
);
}
if (operations?.length) {

View file

@ -604,7 +604,7 @@ export class OrganizationManager {
const owner = await this.getOrganizationOwner(selector);
const { users, organization } = selector;
if (users.some(user => user === owner.id)) {
if (users.includes(owner.id)) {
throw new HiveError(`Cannot remove the owner from the organization`);
}

View file

@ -89,11 +89,11 @@ export class ArtifactStorageReader {
}
return { type: 'redirect', location: await this.generatePresignedGetUrl(key) } as const;
} else if (response.status === 404) {
return { type: 'notFound' } as const;
} else {
const body = await response.text();
throw new Error(`HEAD request failed with status ${response.status}: ${body}`);
}
if (response.status === 404) {
return { type: 'notFound' } as const;
}
const body = await response.text();
throw new Error(`HEAD request failed with status ${response.status}: ${body}`);
}
}

View file

@ -130,7 +130,7 @@ export class SchemaPublisher {
project: input.project,
target: input.target,
},
baseSchema: baseSchema,
baseSchema,
experimental_acceptBreakingChanges: false,
project,
});
@ -496,7 +496,7 @@ export class SchemaPublisher {
project: projectId,
target: targetId,
},
baseSchema: baseSchema,
baseSchema,
experimental_acceptBreakingChanges: input.experimental_acceptBreakingChanges === true,
project,
});

View file

@ -59,7 +59,7 @@ export class SchemaValidator {
return {
id: schema.id,
author: schema.author,
source: source,
source,
date: schema.date,
commit: schema.commit,
url: schema.url,
@ -92,7 +92,7 @@ export class SchemaValidator {
if (isInitialSchema) {
return {
valid: errors.length === 0,
errors: errors,
errors,
changes: [],
messages: [],
};

View file

@ -182,14 +182,13 @@ export class IdempotentRunner {
},
ttl,
});
} else {
this.logger.debug(
'Job created (id=%s, traceId=%s, attempt=%s)',
identifier,
traceId,
context.attempt,
);
}
this.logger.debug(
'Job created (id=%s, traceId=%s, attempt=%s)',
identifier,
traceId,
context.attempt,
);
this.logger.debug(
'Executing job (id=%s, traceId=%s, attempt=%s)',

View file

@ -9,13 +9,14 @@ async function gatherResponse(response: Response) {
if (contentType.includes('json')) {
return JSON.stringify(await response.json());
} else if (contentType.includes('application/text')) {
return response.text();
} else if (contentType.startsWith('text/')) {
return response.text();
} else {
}
if (contentType.includes('application/text')) {
return response.text();
}
if (contentType.startsWith('text/')) {
return response.text();
}
return response.text();
}
export async function handleRequest(request: Request, keyValidator: typeof isSignatureValid) {

View file

@ -122,9 +122,11 @@ export const createArtifactRequestHandler = (deps: ArtifactRequestHandler) => {
return new Response('', {
status: 304,
});
} else if (result.type === 'notFound') {
}
if (result.type === 'notFound') {
return new Response('Not found.', { status: 404 });
} else if (result.type === 'redirect') {
}
if (result.type === 'redirect') {
return new Response('Found.', { status: 302, headers: { Location: result.location } });
}
},

View file

@ -129,7 +129,8 @@ export function createScheduler(config: {
onError('redis:reconnectOnError')(error);
if (clientCommandMessageReg.test(error.message)) {
return false;
} else return 1;
}
return 1;
},
db: 0,
maxRetriesPerRequest: null,

View file

@ -26,24 +26,23 @@ const composeFederation = compose(services => {
})),
},
};
} else {
if (!result.supergraphSdl) {
return {
type: 'failure',
result: {
errors: [{ message: 'supergraphSdl not defined' }],
},
};
}
}
if (!result.supergraphSdl) {
return {
type: 'success',
type: 'failure',
result: {
supergraph: result.supergraphSdl,
sdl: printSchema(result.schema.toGraphQLJSSchema()),
errors: [{ message: 'supergraphSdl not defined' }],
},
};
}
return {
type: 'success',
result: {
supergraph: result.supergraphSdl,
sdl: printSchema(result.schema.toGraphQLJSSchema()),
},
};
} catch (e) {
return {
type: 'failure',
@ -87,15 +86,14 @@ export const createRequestListener = (env: ResolvedEnv): ReturnType<typeof creat
if (error) {
return new Response(error, { status: 500 });
} else {
const result = composeFederation(JSON.parse(body));
return new Response(JSON.stringify(result), {
status: 200,
headers: {
'content-type': 'application/json',
},
});
}
const result = composeFederation(JSON.parse(body));
return new Response(JSON.stringify(result), {
status: 200,
headers: {
'content-type': 'application/json',
},
});
}
return new Response('', {

View file

@ -13,7 +13,7 @@ async function execute(
Authorization: `Bearer ${CF_BEARER_TOKEN}`,
'Content-type': 'application/json',
Accept: 'application/json',
...(options.headers || {}),
...options.headers,
},
...options,
};

View file

@ -222,9 +222,8 @@ export function createRateLimiter(config: {
if (input.type === 'operations-reporting') {
return orgData.operations;
} else {
return UNKNOWN_RATE_LIMIT_OBJ;
}
return UNKNOWN_RATE_LIMIT_OBJ;
},
async start() {
logger.info(

View file

@ -154,7 +154,7 @@ export function createProcessor(config: { logger: FastifyLoggerInstance }) {
operation_kind: normalized.type,
coordinates: normalized.coordinates,
expires_at: group.operation.expiresAt || timestamp + 30 * DAY_IN_MS,
timestamp: timestamp,
timestamp,
}),
);
}
@ -207,7 +207,7 @@ function processSingleOperation(
: operation.timestamp;
return {
timestamp: timestamp,
timestamp,
expiresAt: operation.expiresAt || timestamp + 30 * DAY_IN_MS,
target,
execution,

View file

@ -363,7 +363,7 @@ const Page = ({ organization }: { organization: OrganizationFieldsFragment }) =>
})}
{invitations?.length ? (
<div className="pt-3">
<div className="border-t-4 border-solid pb-6"></div>
<div className="border-t-4 border-solid pb-6" />
{invitations.map(node => (
<Invitation key={node.id} invitation={node} organizationCleanId={org.cleanId} />
))}

View file

@ -135,7 +135,7 @@ const Inner = ({
monthlyLimits: {
operations: operationsRateLimit * 1_000_000,
},
paymentMethodId: paymentMethodId,
paymentMethodId,
couponCode: couponCode.trim() === '' ? null : couponCode.trim(),
});
};

View file

@ -25,7 +25,7 @@ export async function ensureGithubIntegration(
variables: {
input: {
organization: orgId,
installationId: installationId,
installationId,
},
},
});

View file

@ -130,7 +130,7 @@ async function graphql(req: NextApiRequest, res: NextApiResponse) {
const message = (error as Record<string, unknown | undefined>)?.['message'] ?? '';
res.status(status).json({
code: code,
code,
error: message,
});
}

View file

@ -40,7 +40,7 @@ export const OrganizationUsageEstimationView: React.FC<{
<Th>Feature</Th>
<Th isNumeric>Used</Th>
<Th isNumeric>Limit</Th>
<Th></Th>
<Th />
</Tr>
</Thead>
<Tbody>

View file

@ -58,7 +58,7 @@ export const ProjectSwitcher: React.FC<{
<MenuItem
onClick={() => {
router.visitProject({
organizationId: organizationId,
organizationId,
projectId: item.cleanId,
});
}}

View file

@ -96,7 +96,7 @@ const OperationsFilter: React.FC<{
style={style}
key={operation.id}
operation={operation}
selected={selectedItems.some(operationHash => operationHash === operation.operationHash)}
selected={selectedItems.includes(operation.operationHash || '')}
onSelect={onSelect}
/>
);

View file

@ -423,7 +423,8 @@ const OperationsTableContainer: React.FC<{
const maxPageIndex = Math.ceil(data.length / state.pageSize) - 1;
if (state.pageIndex < 0) {
return { ...state, pageIndex: 0 };
} else if (state.pageIndex > maxPageIndex) {
}
if (state.pageIndex > maxPageIndex) {
return { ...state, pageIndex: maxPageIndex };
}
return state;

View file

@ -378,17 +378,15 @@ const ClientsStats: React.FC<{
if (i < 4) {
counts.push(client.count);
labels.push(client.name);
} else if (!labels[4]) {
counts.push(client.count);
labels.push(
sortedClients.length === 5
? client.name
: `Other clients (${sortedClients.length - 4})`,
);
} else {
if (!labels[4]) {
counts.push(client.count);
labels.push(
sortedClients.length === 5
? client.name
: `Other clients (${sortedClients.length - 4})`,
);
} else {
counts[4] += client.percentage;
}
counts[4] += client.percentage;
}
}
@ -429,15 +427,13 @@ const ClientsStats: React.FC<{
if (i < 4) {
counts.push(version.count);
labels.push(version.name);
} else if (!labels[4]) {
counts.push(version.count);
labels.push(
versions.length === 5 ? version.name : `Other versions (${versions.length - 4})`,
);
} else {
if (!labels[4]) {
counts.push(version.count);
labels.push(
versions.length === 5 ? version.name : `Other versions (${versions.length - 4})`,
);
} else {
counts[4] += version.count;
}
counts[4] += version.count;
}
}

View file

@ -126,7 +126,7 @@ export const backendConfig = (): TypeInput => {
functions: originalImplementation => {
return {
...originalImplementation,
createNewSession: async function (input) {
async createNewSession(input) {
const user = await ThirdPartyEmailPasswordNode.getUserById(input.userId);
if (!user) {
@ -468,7 +468,7 @@ async function trySignIntoAuth0WithUserCredentialsAndRetrieveUserInfo(
client_secret: config.clientSecret,
grant_type: 'password',
username: email,
password: password,
password,
}),
});

View file

@ -18,7 +18,7 @@ export const event = ({ action, category, label, value }: any): void => {
(window as any).gtag('event', action, {
event_category: category,
event_label: label,
value: value,
value,
});
};

View file

@ -28,7 +28,7 @@ export default class MyDocument extends Document {
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png" />
<link rel="mask-icon" href="/safari-pinned-tab.svg" color="#0B0D11" />
<meta name="msapplication-TileColor" content="#0B0D11" />
<meta name="theme-color" content="#0B0D11"></meta>
<meta name="theme-color" content="#0B0D11" />
</Head>
<body>
<Main />

View file

@ -66,7 +66,7 @@ async function main() {
setInterval(
() => {
for (let i = 0; i < operationsPerBatch; i++) {
let randNumber = Math.random() * 100;
const randNumber = Math.random() * 100;
console.log(`Reporting usage query...`);
const done = hiveInstance.collectUsage({