Skip to content

[RFC] Increase prettier width 80 -> 100 #3494

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
1 change: 1 addition & 0 deletions .prettierrc.yml
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
singleQuote: true
trailingComma: all
printWidth: 100
5 changes: 1 addition & 4 deletions dbschema/seeds/001.root-user.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
import { EnvironmentService } from '~/core/config/environment.service';
import {
determineRootUser,
RootUserAlias,
} from '~/core/config/root-user.config';
import { determineRootUser, RootUserAlias } from '~/core/config/root-user.config';
import type { SeedFn } from '~/core/gel/seeds.run';

export default (async function ({ e, db, print }) {
Expand Down
6 changes: 2 additions & 4 deletions dbschema/seeds/008.projects.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,10 +114,8 @@ export default (async function ({ e, db, print }) {
for (const { type, step, ...project } of newProjects) {
const insertQ = e.insert(e[`${type}Project`], {
...project,
...mapValues.fromList(
['mouStart', 'mouEnd', 'estimatedSubmission'],
(key, { SKIP }) =>
!project[key] ? SKIP : e.cal.local_date(project[key]!),
...mapValues.fromList(['mouStart', 'mouEnd', 'estimatedSubmission'], (key, { SKIP }) =>
!project[key] ? SKIP : e.cal.local_date(project[key]!),
).asRecord,
primaryLocation: project.primaryLocation
? e.assert_exists(
Expand Down
4 changes: 1 addition & 3 deletions jest.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,6 @@ export default async (): Promise<Config.InitialOptions> => {
testTimeout: Duration.fromObject({ minutes: 1 }).toMillis(),
// WebStorm doesn't need this as it adds the cli flag automatically.
// I'm guessing VSCode needs it.
...(debugging
? { testTimeout: Duration.fromObject({ hours: 2 }).toMillis() }
: {}),
...(debugging ? { testTimeout: Duration.fromObject({ hours: 2 }).toMillis() } : {}),
};
};
6 changes: 1 addition & 5 deletions src/common/and-call.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,7 @@ import { type FnLike } from '@seedcompany/common';
import { isPromise } from 'node:util/types';
import { type ConditionalKeys } from 'type-fest';

export const andCall = <
T,
K extends ConditionalKeys<T, FnLike>,
X extends T[K] & FnLike,
>(
export const andCall = <T, K extends ConditionalKeys<T, FnLike>, X extends T[K] & FnLike>(
thing: T,
methodName: K,
add: X,
Expand Down
4 changes: 1 addition & 3 deletions src/common/augmented-metadata.pipe.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,7 @@ import { type ArgumentMetadata, type PipeTransform } from '@nestjs/common';
import { ServerException } from './exceptions';

const key = Symbol('AugmentedMetadata');
export const createAugmentedMetadataPipe = <
T extends Record<string, any>,
>() => {
export const createAugmentedMetadataPipe = <T extends Record<string, any>>() => {
const pipe = (data: T | (() => T)): PipeTransform => ({
transform: (value, metadata) => {
const actual = typeof data === 'function' ? data() : data;
Expand Down
3 changes: 1 addition & 2 deletions src/common/calculated.decorator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,7 @@ export const CalculatedSymbol = Symbol('Calculated');
* This means the resource/property is managed by the API, instead of the user.
*/
export const Calculated =
(): PropertyDecorator & ClassDecorator =>
(target: any, key?: string | symbol) => {
(): PropertyDecorator & ClassDecorator => (target: any, key?: string | symbol) => {
if (!key) {
Reflect.defineMetadata(CalculatedSymbol, true, target);
return target;
Expand Down
4 changes: 1 addition & 3 deletions src/common/discovery-unique-methods.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
import { type DiscoveredMethodWithMeta } from '@golevelup/nestjs-discovery';

export const uniqueDiscoveredMethods = <T>(
methods: Array<DiscoveredMethodWithMeta<T>>,
) => {
export const uniqueDiscoveredMethods = <T>(methods: Array<DiscoveredMethodWithMeta<T>>) => {
const seenClasses = new Map<object, Map<string, Set<unknown>>>();
const uniqueMethods = [] as typeof methods;
for (const method of methods) {
Expand Down
10 changes: 2 additions & 8 deletions src/common/exceptions/creation-failed.exception.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,21 +4,15 @@ import { ServerException } from './exception';

export class CreationFailed extends ServerException {
readonly resource: EnhancedResource<any>;
constructor(
resource: ResourceLike,
options?: { message?: string; cause?: Error },
) {
constructor(resource: ResourceLike, options?: { message?: string; cause?: Error }) {
const res = EnhancedResource.resolve(resource);
super(options?.message ?? `Failed to create ${res.name}`, options?.cause);
this.resource = res;
}
}

export class ReadAfterCreationFailed extends CreationFailed {
constructor(
resource: ResourceLike,
options?: { message?: string; cause?: Error },
) {
constructor(resource: ResourceLike, options?: { message?: string; cause?: Error }) {
const res = EnhancedResource.resolve(resource);
super(res, {
message: `Failed to retrieve ${res.name} after creation`,
Expand Down
34 changes: 16 additions & 18 deletions src/common/exceptions/date-override-conflict.exception.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,24 +48,22 @@ export class DateOverrideConflictException extends RangeException {
end: CalendarDate | null;
}>,
): NonEmptyArray<Conflict> | undefined {
const maybeConflicts = items.flatMap<Conflict | null>(
({ start, end, ...item }) => [
canonical.start && start && canonical.start > start
? {
...item,
point: 'start' as const,
date: start,
}
: null,
canonical.end && end && canonical.end < end
? {
...item,
point: 'end' as const,
date: end,
}
: null,
],
);
const maybeConflicts = items.flatMap<Conflict | null>(({ start, end, ...item }) => [
canonical.start && start && canonical.start > start
? {
...item,
point: 'start' as const,
date: start,
}
: null,
canonical.end && end && canonical.end < end
? {
...item,
point: 'end' as const,
date: end,
}
: null,
]);
return asNonEmpty(maybeConflicts.filter(isNotFalsy));
}
}
Expand Down
16 changes: 5 additions & 11 deletions src/common/exceptions/duplicate.exception.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,25 +8,19 @@ import { InputException } from './input.exception';
*/
export class DuplicateException extends InputException {
constructor(field: string, message?: string, previous?: Error) {
super(
message ?? `${field} already exists and needs to be unique`,
field,
previous,
);
super(message ?? `${field} already exists and needs to be unique`, field, previous);
}

static fromDB(exception: ExclusivityViolationError, context?: ArgumentsHost) {
let property = exception.property;
const message = `${upperFirst(
lowerCase(property),
)} already exists and needs to be unique`;
const message = `${upperFirst(lowerCase(property))} already exists and needs to be unique`;

// Attempt to add path prefix automatically to the property name, based
// on given GQL input.
// This kinda assumes the property name will be unique amongst all the input.
const guessedPath = Object.keys(
InputException.getFlattenInput(context),
).find((path) => property === path || path.endsWith('.' + property));
const guessedPath = Object.keys(InputException.getFlattenInput(context)).find(
(path) => property === path || path.endsWith('.' + property),
);
property = guessedPath ?? property;

return new DuplicateException(property, message, exception);
Expand Down
19 changes: 4 additions & 15 deletions src/common/exceptions/input.exception.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,7 @@ import { type ArgumentsHost } from '@nestjs/common';
import { GqlExecutionContext } from '@nestjs/graphql';
import { ClientException } from './exception';

export type InputExceptionArgs =
| [Error?]
| [string, Error?]
| [string, string?, Error?];
export type InputExceptionArgs = [Error?] | [string, Error?] | [string, string?, Error?];

/**
* Indicate the request cannot be completed because of requester has done
Expand Down Expand Up @@ -71,10 +68,7 @@ export class InputException extends ClientException {
constructor(message: string, field?: string, previous?: Error);

constructor(...args: InputExceptionArgs) {
const [message, field, previous] = InputException.parseArgs(
'Invalid request',
args,
);
const [message, field, previous] = InputException.parseArgs('Invalid request', args);
super(message, previous);
this.field = field;
}
Expand All @@ -84,10 +78,7 @@ export class InputException extends ClientException {
return this;
}

static parseArgs(
defaultMessage: string,
[one, two, three]: InputExceptionArgs,
) {
static parseArgs(defaultMessage: string, [one, two, three]: InputExceptionArgs) {
let message = defaultMessage;
let field;
let previous;
Expand All @@ -112,9 +103,7 @@ export class InputException extends ClientException {
return {};
}
const gqlContext =
context instanceof GqlExecutionContext
? context
: GqlExecutionContext.create(context as any);
context instanceof GqlExecutionContext ? context : GqlExecutionContext.create(context as any);
let gqlArgs = gqlContext.getArgs();

// unwind single `input` argument, based on our own conventions
Expand Down
4 changes: 1 addition & 3 deletions src/common/exceptions/unauthorized.exception.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,9 +87,7 @@ export class UnauthorizedException extends InputException {
const scope = object ? 'this' : 'any';
if (action === 'create') {
const message = edges
? `${prefix} create ${edges} for ${scope} ${
object ? resourceName : resources
}`
? `${prefix} create ${edges} for ${scope} ${object ? resourceName : resources}`
: `${prefix} create ${resources}`;
return new UnauthorizedException(message);
}
Expand Down
9 changes: 2 additions & 7 deletions src/common/field-selection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,19 +71,14 @@ export class FieldSelection {
* to filter out requested but unrelated fields.
*/
forType<T>(type: AbstractClassType<T>): FieldInfo<T>;
forType<K extends keyof ResourceMap>(
type: K,
): FieldInfo<ResourceMap[K]['prototype']>;
forType<K extends keyof ResourceMap>(type: K): FieldInfo<ResourceMap[K]['prototype']>;
forType(type: string | AbstractClassType<any>) {
const typeName = typeof type === 'string' ? type : type.constructor.name;
const typeObj = this.resolveInfo.schema.getType(typeName);
if (!typeObj) {
return {};
}
const { fields } = simplifyParsedResolveInfoFragmentWithType(
this.tree,
typeObj,
);
const { fields } = simplifyParsedResolveInfoFragmentWithType(this.tree, typeObj);
return fields;
}

Expand Down
16 changes: 4 additions & 12 deletions src/common/firstLettersOfWords.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,22 +24,14 @@ const lowercasePattern = RegExp(
const matchAndMerge = (pattern: RegExp, str: string, group = 1) =>
Array.from(str.matchAll(pattern), (m) => m[group]).join('');

export function firstLettersOfWords(
words: string,
limit: number | null = 3,
): string {
export function firstLettersOfWords(words: string, limit: number | null = 3): string {
// If the string has uppercase characters we use the uppercase pattern which
// will ignore lowercase characters after word-like boundaries.
// If the string doesn't have any uppercase characters we fallback to the lowercase pattern
// which is less ideal but gives something instead of an empty string.
// See tests for differences in the two patterns.
const pattern = words.match(hasUppercaseLettersPattern)
? uppercasePattern
: lowercasePattern;
const letters =
matchAndMerge(pattern, words) || matchAndMerge(lowercasePattern, words);
const pattern = words.match(hasUppercaseLettersPattern) ? uppercasePattern : lowercasePattern;
const letters = matchAndMerge(pattern, words) || matchAndMerge(lowercasePattern, words);

return limit === Infinity || limit == null
? letters
: letters.slice(0, limit);
return limit === Infinity || limit == null ? letters : letters.slice(0, limit);
}
4 changes: 1 addition & 3 deletions src/common/fiscal-year.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,6 @@ describe('fullFiscalQuarter', () => {
[3, 2020, '2020-04-01/2020-06-30'],
[4, 2020, '2020-07-01/2020-09-30'],
])('Q%s FY%s -> %s', (fiscalQuarter, fiscalYear, dateRange) => {
expect(fullFiscalQuarter(fiscalQuarter, fiscalYear).toISO()).toEqual(
dateRange,
);
expect(fullFiscalQuarter(fiscalQuarter, fiscalYear).toISO()).toEqual(dateRange);
});
});
19 changes: 5 additions & 14 deletions src/common/fiscal-year.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,7 @@ export const fiscalYear = (dt: DateTime) => dt.year + (dt.month >= 10 ? 1 : 0);
export const fiscalYears = (start?: DateTime, end?: DateTime) =>
start && end ? range(fiscalYear(start), fiscalYear(end) + 1) : [];

export const fiscalQuarter = (dt: DateTime) =>
dt.quarter === 4 ? 1 : dt.quarter + 1;
export const fiscalQuarter = (dt: DateTime) => (dt.quarter === 4 ? 1 : dt.quarter + 1);

export const startOfFiscalYear = (date: CalendarDate) =>
CalendarDate.local(date.year - (date.month >= 10 ? 0 : 1), 10, 1);
Expand All @@ -20,10 +19,7 @@ export const endOfFiscalYear = (date: CalendarDate) =>
CalendarDate.local(date.year + (date.month >= 10 ? 1 : 0), 9, 30);

export const expandToFullFiscalYears = (dates: DateInterval) =>
DateInterval.fromDateTimes(
startOfFiscalYear(dates.start),
endOfFiscalYear(dates.end),
);
DateInterval.fromDateTimes(startOfFiscalYear(dates.start), endOfFiscalYear(dates.end));

export const fullFiscalYear = (fiscalYear: number) =>
DateInterval.fromDateTimes(
Expand All @@ -32,10 +28,7 @@ export const fullFiscalYear = (fiscalYear: number) =>
);

/** The date interval of a given fiscal quarter */
export const fullFiscalQuarter = (
fiscalQuarter: number,
fiscalYear: number,
) => {
export const fullFiscalQuarter = (fiscalQuarter: number, fiscalYear: number) => {
const year = fiscalYear + (fiscalQuarter === 1 ? -1 : 0);
const quarter = fiscalQuarter + (fiscalQuarter === 1 ? 2 : -2);
const fiscalQuarterStartDate = CalendarDate.local(year, 1, 1).plus({
Expand All @@ -48,11 +41,9 @@ export const fullFiscalQuarter = (
);
};

export const isReasonableYear = (year: unknown) =>
isInt(year) && year >= 1970 && year <= 3000;
export const isReasonableYear = (year: unknown) => isInt(year) && year >= 1970 && year <= 3000;

export const isQuarterNumber = (quarter: unknown) =>
isInt(quarter) && quarter >= 1 && quarter <= 4;
export const isQuarterNumber = (quarter: unknown) => isInt(quarter) && quarter >= 1 && quarter <= 4;

// Not true for falsy case, thus not built-in, but fine for our cases here.
const isInt = (x: unknown): x is number => Number.isInteger(x);
9 changes: 5 additions & 4 deletions src/common/generate-id.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,13 @@ import { type ID } from './id-field';

// 100 IDs / hour = 1k years to have 1% probability of a single collision
// https://zelark.github.io/nano-id-cc/
const alphabet =
'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
const alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
const size = 11;

export const generateId: <TID extends ID = ID>() => Promise<TID> =
customAlphabet(alphabet, size) as any;
export const generateId: <TID extends ID = ID>() => Promise<TID> = customAlphabet(
alphabet,
size,
) as any;

export const isValidId = (value: unknown): value is ID => {
if (typeof value !== 'string') {
Expand Down
3 changes: 1 addition & 2 deletions src/common/id-field.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,7 @@ const UserIncompatibleDifferent: ID<'User'> = '' as ID<'Location'>;
// @ts-expect-error this should be blocked
const UserIncompatibleDifferent2: ID<'Location'> = '' as ID<'User'>;

const SubclassesAreCompatible: ID<'Engagement'> =
'' as ID<'LanguageEngagement'>;
const SubclassesAreCompatible: ID<'Engagement'> = '' as ID<'LanguageEngagement'>;
// @ts-expect-error this should be blocked
const InterfaceIsNotDirectlyCompatibleWithConcrete: ID<'LanguageEngagement'> =
'' as ID<'Engagement'>;
Expand Down
6 changes: 2 additions & 4 deletions src/common/id-field.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,9 @@ export const IdField = ({
IsId(validation),
);

export const isIdLike = (value: unknown): value is ID =>
typeof value === 'string';
export const isIdLike = (value: unknown): value is ID => typeof value === 'string';

export type ID<Kind extends IDKindLike = any> = Tagged<string, 'ID'> &
IDTo<IDTag<Kind>>;
export type ID<Kind extends IDKindLike = any> = Tagged<string, 'ID'> & IDTo<IDTag<Kind>>;

/** @deprecated Use {@link ID} */
export type IdOf<Kind extends IDKindLike> = ID<Kind>;
Expand Down
3 changes: 1 addition & 2 deletions src/common/id.arg.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,4 @@ import { ValidateIdPipe } from './validators/short-id.validator';
export const IdArg = (
opts: Partial<ArgsOptions> = {},
...pipes: Array<Type<PipeTransform> | PipeTransform>
) =>
Args({ name: 'id', type: () => IdType, ...opts }, ValidateIdPipe, ...pipes);
) => Args({ name: 'id', type: () => IdType, ...opts }, ValidateIdPipe, ...pipes);
Loading
Loading