Skip to content

Commit

Permalink
base lint passing
Browse files Browse the repository at this point in the history
  • Loading branch information
revmischa committed Jul 2, 2024
1 parent b5c13a2 commit 13c9765
Show file tree
Hide file tree
Showing 17 changed files with 386 additions and 607 deletions.
2 changes: 1 addition & 1 deletion .prettierrc.yaml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
tabWidth: 2
semi: false
printWidth: 120
trailingComma: es5
trailingComma: all
singleQuote: true
2 changes: 1 addition & 1 deletion backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
"@aws-sdk/client-kms": "~3.145.0",
"@aws-sdk/client-secrets-manager": "~3.145.0",
"@aws-sdk/signature-v4-crt": "^3.130.0",
"@middy/core": "^2.5.7",
"@middy/core": "^5.4.2",
"@prisma/client": "5.16.1",
"@prisma/internals": "5.16.1",
"@prisma/migrate": "5.16.1",
Expand Down
24 changes: 10 additions & 14 deletions backend/src/api/resolver/greeting.test.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,18 @@
import { testCallResolver } from '../../util/testResolver';
import { GREETING } from './greeting';

const { getGreeting, greetInner } = await import('./greeting');
import { testCallResolver } from '../../util/testResolver'
import { getGreeting, GREETING, greetInner } from './greeting'

describe('Greeting resolvers', () => {
it('gets current greeting', async () => {
const greeting = await testCallResolver({
args: {},
resolverFunc: getGreeting,
});
expect(greeting.currentGreeting).toBe(GREETING);
});
const greeting = getGreeting()
expect(greeting.currentGreeting).toBe(GREETING)
})

it('greets user by name', async () => {
const greeting = await testCallResolver({
userName: 'cognitoUsername',
args: { name: 'Lebowski' },
resolverFunc: greetInner,
});
expect(greeting.greeting).toBe(`${GREETING}, Lebowski!`);
});
});
})
expect(greeting.greeting).toBe(`${GREETING}, Lebowski!`)
})
})
16 changes: 8 additions & 8 deletions backend/src/db/seed/fakeSampleData.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,26 @@
import { truncateAllTables } from '@backend/db/seed/truncate';
import { userFactory } from '@backend/db/factory/user';
import { Prisma } from '@prisma/client';
import { truncateAllTables } from '@backend/db/seed/truncate'
import { userFactory } from '@backend/db/factory/user'
import { Prisma } from '@prisma/client'

const { prisma } = await import('@backend/db/clientSync');
const { prisma } = await import('@backend/db/clientSync')

export async function seedFakerSampleData() {
prisma.$transaction(startSeeding, { maxWait: 30_000, timeout: 60_000 });
await prisma.$transaction(startSeeding, { maxWait: 30_000, timeout: 60_000 })
}

export async function startSeeding(prisma: Prisma.TransactionClient) {
if (process.env.CLEAN_SEED) {
// Remove old data
truncateAllTables(prisma);
await truncateAllTables(prisma)
}

// Create 5 fake users with generated data
await prisma.user.createMany({ data: userFactory.buildList(5) });
await prisma.user.createMany({ data: userFactory.buildList(5) })
// Create 1 user with some custom data
await prisma.user.create({
data: userFactory.build({
name: 'Robert Lewandowski',
email: 'lewa@fcbarcelona.com',
}),
});
})
}
32 changes: 16 additions & 16 deletions backend/src/db/testUtil.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,22 @@
import { PrismaTestingHelper } from '@chax-at/transactional-prisma-testing';
import { truncateAllTables } from '@backend/db/seed/truncate';
import { PrismaClient } from '@prisma/client';
import { PrismaTestingHelper } from '@chax-at/transactional-prisma-testing'
import { truncateAllTables } from '@backend/db/seed/truncate'
import { PrismaClient } from '@prisma/client'

const prismaClient = new PrismaClient();
await truncateAllTables(prismaClient); // can be skipped for speed maybe
const prismaClient = new PrismaClient()
await truncateAllTables(prismaClient) // can be skipped for speed maybe

// create prisma proxy to wrap all tests in a transaction
const prismaTestingHelper = new PrismaTestingHelper(prismaClient);
const prismaTestingHelper = new PrismaTestingHelper(prismaClient)
vi.mock('@backend/db/client', async () => {
const actual = await vi.importActual<typeof import('@backend/db/client')>('@backend/db/client');
const actual = await vi.importActual<typeof import('@backend/db/client')>('@backend/db/client')

return {
...actual,
getPrisma: async () => {
return prismaTestingHelper.getProxyClient();
return prismaTestingHelper.getProxyClient()
},
};
});
}
})

/**
* Define a database integration test suite.
Expand All @@ -26,12 +26,12 @@ vi.mock('@backend/db/client', async () => {
*/
export const describeIntegrationTest = (title: string, inner: () => void) => {
beforeEach(async () => {
await prismaTestingHelper.startNewTransaction();
});
await prismaTestingHelper.startNewTransaction()
})

afterEach(async () => {
await prismaTestingHelper?.rollbackCurrentTransaction();
});
prismaTestingHelper?.rollbackCurrentTransaction()
})

describe(title, inner);
};
describe(title, inner)
}
51 changes: 25 additions & 26 deletions backend/src/middleware/lambda.ts
Original file line number Diff line number Diff line change
@@ -1,36 +1,35 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { injectLambdaContext } from '@aws-lambda-powertools/logger';
import { logMetrics } from '@aws-lambda-powertools/metrics';
import { captureLambdaHandler } from '@aws-lambda-powertools/tracer';
import { logger } from '@backend/util/logger';
import { metrics } from '@backend/util/metrics';
import { tracer } from '@backend/util/tracer';
import middy from '@middy/core';
import { Callback, Context } from 'aws-lambda';
import { wrapLambdaHandlerWithSentry } from './sentryLambdaWrapper';
import { appSyncXrayMiddleware } from './xray';
import { injectLambdaContext } from '@aws-lambda-powertools/logger'
import { logMetrics } from '@aws-lambda-powertools/metrics'
import { captureLambdaHandler } from '@aws-lambda-powertools/tracer'
import { logger } from '@backend/util/logger'
import { metrics } from '@backend/util/metrics'
import { tracer } from '@backend/util/tracer'
import middy from '@middy/core'
import { Callback, Context } from 'aws-lambda'
import { wrapLambdaHandlerWithSentry } from './sentryLambdaWrapper'
import { appSyncXrayMiddleware } from './xray'

export type Handler<TEvent = unknown, TResult = unknown> = (
event: TEvent,
context: Context,
callback: Callback<TResult>
) => void | Promise<TResult>;
callback: Callback<TResult>,
) => void | Promise<TResult>

const DEFAULT_MIDDLEWARE = [
injectLambdaContext(logger),
captureLambdaHandler(tracer),
logMetrics(metrics, { captureColdStartMetric: true }),
];
]

const DEFAULT_APPSYNC_MIDDLEWARE = [
...DEFAULT_MIDDLEWARE,

// add xray annotations
appSyncXrayMiddleware(),
];
]

// if you want it
const isSentryEnabled = false;
const isSentryEnabled = false

/**
* Default middleware to apply to all resolver functions.
Expand All @@ -39,24 +38,24 @@ const isSentryEnabled = false;
export const defaultAppSyncMiddleware = <T extends (...args: any[]) => any>() => {
return (resolverFunc: T) => {
// apply middleware
const handlerWithMiddlewares = middy(resolverFunc).use(DEFAULT_APPSYNC_MIDDLEWARE);
const handlerWithMiddlewares = middy(resolverFunc).use(DEFAULT_APPSYNC_MIDDLEWARE)

// sentry wrapper
if (isSentryEnabled) return wrapLambdaHandlerWithSentry(handlerWithMiddlewares);
else return handlerWithMiddlewares;
};
};
if (isSentryEnabled) return wrapLambdaHandlerWithSentry(handlerWithMiddlewares)
else return handlerWithMiddlewares
}
}

/**
* Middleware for any lambda function.
*/
export const defaultLambdaMiddleware = <T extends (...args: any[]) => any>() => {
return (resolverFunc: T) => {
// apply middleware
const handlerWithMiddlewares = middy(resolverFunc).use(DEFAULT_MIDDLEWARE);
const handlerWithMiddlewares = middy(resolverFunc).use(DEFAULT_MIDDLEWARE)

// sentry wrapper
if (isSentryEnabled) return wrapLambdaHandlerWithSentry(handlerWithMiddlewares);
else return handlerWithMiddlewares;
};
};
if (isSentryEnabled) return wrapLambdaHandlerWithSentry(handlerWithMiddlewares)
else return handlerWithMiddlewares
}
}
45 changes: 22 additions & 23 deletions backend/src/util/testResolver.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { AppSyncIdentity, AppSyncResolverEvent, Callback, Context } from 'aws-lambda';
import { AppSyncResolverHandler, Context } from 'aws-lambda'

export interface TestCallResolverArgs<A, R, S> {
userName?: string;
resolverFunc: (event: AppSyncResolverEvent<A, S>, context?: Context, callback?: Callback) => R;
args: A;
source?: S;
type InferFunc<T> = T extends (...p: infer P) => infer R | void ? (...p: P) => R : never

export interface CallAuthenticatedResolver<A, R, S> {
userName: string
resolverFunc: InferFunc<AppSyncResolverHandler<A, R, S>>
args: A
source?: S
}

/**
Expand All @@ -18,29 +19,27 @@ export const testCallResolver = <A, R, S>({
args,
source = null as unknown as S,
resolverFunc,
}: TestCallResolverArgs<A, R, S>) =>
}: CallAuthenticatedResolver<A, R, S>) =>
resolverFunc(
{
arguments: args,
identity: userName
? {
sub: userName,
issuer: 'King Mischa',
sourceIp: ['1.2.3.4'],
defaultAuthStrategy: 'whatever',
groups: [],
claims: { 'cognito:username': userName },
username: userName,
}
: ({} as AppSyncIdentity),
identity: {
sub: userName,
issuer: 'King Mischa',
sourceIp: ['1.2.3.4'],
defaultAuthStrategy: 'whatever',
groups: [],
claims: { 'cognito:username': userName },
username: userName,
},
source,
info: {} as any,
info: { selectionSetList: [] } as any,
prev: {} as any,
request: {} as any,
stash: {} as any,
},
{} as Context,
() => {
throw new Error("don't call lambda callback");
}
);
throw new Error("don't call lambda callback")
},
)
Loading

0 comments on commit 13c9765

Please sign in to comment.