Skip to content

Commit

Permalink
chore(adapter-nextjs): migrate to eslint
Browse files Browse the repository at this point in the history
  • Loading branch information
HuiSF committed Jan 29, 2024
1 parent 791c8f4 commit ef28a20
Show file tree
Hide file tree
Showing 7 changed files with 50 additions and 104 deletions.
3 changes: 2 additions & 1 deletion packages/adapter-nextjs/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,8 @@
"clean": "npm run clean:size && rimraf dist",
"clean:size": "rimraf dual-publish-tmp tmp*",
"format": "echo \"Not implemented\"",
"lint": "tslint 'src/**/*.ts' && npm run ts-coverage",
"lint": "eslint '**/*.{ts,tsx}' && npm run ts-coverage",
"lint:fix": "eslint '**/*.{ts,tsx}' --fix",
"test": "npm run lint && jest -w 1 --coverage --logHeapUsage",
"ts-coverage": "typescript-coverage-report -p ./tsconfig.build.json -t 90.31"
}
Expand Down
1 change: 1 addition & 0 deletions packages/adapter-nextjs/src/createServerRunner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// SPDX-License-Identifier: Apache-2.0

import { ResourcesConfig } from 'aws-amplify';

import { createRunWithAmplifyServerContext, getAmplifyConfig } from './utils';
import { NextServer } from './types';

Expand Down
41 changes: 18 additions & 23 deletions packages/adapter-nextjs/src/types/NextServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,38 +8,38 @@ import { LegacyConfig } from 'aws-amplify/adapter-core';
import { AmplifyServer } from '@aws-amplify/core/internals/adapter-core';
import { ResourcesConfig } from '@aws-amplify/core';

export namespace NextServer {
export declare namespace NextServer {
/**
* This context is normally available in the following:
* - Next App Router [middleware](https://nextjs.org/docs/app/building-your-application/routing/middleware)
* - Next App Router [route handler](https://nextjs.org/docs/app/building-your-application/routing/route-handlers)
* when using `NextResponse` to create the response of the route handler
*/
export type NextRequestAndNextResponseContext = {
export interface NextRequestAndNextResponseContext {
request: NextRequest;
response: NextResponse;
};
}

/**
* This context is normally available in the following:
* - Next App Router [route handler](https://nextjs.org/docs/app/building-your-application/routing/route-handlers)
* when using the Web API [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
* to create the response of the route handler
*/
export type NextRequestAndResponseContext = {
export interface NextRequestAndResponseContext {
request: NextRequest;
response: Response;
};
}

/**
* This context is normally available in the following:
* - Next [Server Component](https://nextjs.org/docs/getting-started/react-essentials#server-components)
* where the [`cookies`](https://nextjs.org/docs/app/api-reference/functions/cookies)
* function can be imported and called
*/
export type ServerComponentContext = {
export interface ServerComponentContext {
cookies: typeof cookies;
};
}

export type ServerActionContext = ServerComponentContext;

Expand All @@ -48,10 +48,10 @@ export namespace NextServer {
* [`getServerSideProps`](https://nextjs.org/docs/pages/building-your-application/data-fetching/get-server-side-props)
* function of the Next Pages Router.
*/
export type GetServerSidePropsContext = {
export interface GetServerSidePropsContext {
request: NextGetServerSidePropsContext['req'];
response: NextGetServerSidePropsContext['res'];
};
}

/**
* The union of possible Next.js app server context types.
Expand All @@ -62,21 +62,16 @@ export namespace NextServer {
| ServerComponentContext
| GetServerSidePropsContext;

/**
* The interface of the input of {@link RunOperationWithContext}.
*/
export interface RunWithContextInput<OperationResult> {
nextServerContext: Context | null;
operation: (
contextSpec: AmplifyServer.ContextSpec
) => OperationResult | Promise<OperationResult>;
operation(
contextSpec: AmplifyServer.ContextSpec,
): OperationResult | Promise<OperationResult>;
}

export interface RunOperationWithContext {
<OperationResult>(
input: RunWithContextInput<OperationResult>
): Promise<OperationResult>;
}
export type RunOperationWithContext = <OperationResult>(
input: RunWithContextInput<OperationResult>,
) => Promise<OperationResult>;

export interface CreateServerRunnerInput {
config: ResourcesConfig | LegacyConfig;
Expand All @@ -86,7 +81,7 @@ export namespace NextServer {
runWithAmplifyServerContext: RunOperationWithContext;
}

export interface CreateServerRunner {
(input: CreateServerRunnerInput): CreateServerRunnerOutput;
}
export type CreateServerRunner = (
input: CreateServerRunnerInput,
) => CreateServerRunnerOutput;
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,17 @@
// SPDX-License-Identifier: Apache-2.0

import { NextRequest, NextResponse } from 'next/server.js';
import { NextServer } from '../types';
import {
AmplifyServerContextError,
CookieStorage,
} from '@aws-amplify/core/internals/adapter-core';

import { NextServer } from '../types';

export const DATE_IN_THE_PAST = new Date(0);

export const createCookieStorageAdapterFromNextServerContext = (
context: NextServer.Context
context: NextServer.Context,
): CookieStorage.Adapter => {
const { request: req, response: res } =
context as Partial<NextServer.GetServerSidePropsContext>;
Expand Down Expand Up @@ -45,12 +46,12 @@ export const createCookieStorageAdapterFromNextServerContext = (
if (response instanceof NextResponse) {
return createCookieStorageAdapterFromNextRequestAndNextResponse(
request,
response
response,
);
} else {
return createCookieStorageAdapterFromNextRequestAndHttpResponse(
request,
response
response,
);
}
}
Expand All @@ -72,7 +73,7 @@ export const createCookieStorageAdapterFromNextServerContext = (

const createCookieStorageAdapterFromNextRequestAndNextResponse = (
request: NextRequest,
response: NextResponse
response: NextResponse,
): CookieStorage.Adapter => {
const readonlyCookieStore = request.cookies;
const mutableCookieStore = response.cookies;
Expand All @@ -93,11 +94,11 @@ const createCookieStorageAdapterFromNextRequestAndNextResponse = (

const createCookieStorageAdapterFromNextRequestAndHttpResponse = (
request: NextRequest,
response: Response
response: Response,
): CookieStorage.Adapter => {
const readonlyCookieStore = request.cookies;
const mutableCookieStore = createMutableCookieStoreFromHeaders(
response.headers
response.headers,
);

return {
Expand All @@ -110,7 +111,7 @@ const createCookieStorageAdapterFromNextRequestAndHttpResponse = (
};

const createCookieStorageAdapterFromNextCookies = (
cookies: NextServer.ServerComponentContext['cookies']
cookies: NextServer.ServerComponentContext['cookies'],
): CookieStorage.Adapter => {
const cookieStore = cookies();

Expand Down Expand Up @@ -147,7 +148,7 @@ const createCookieStorageAdapterFromNextCookies = (

const createCookieStorageAdapterFromGetServerSidePropsContext = (
request: NextServer.GetServerSidePropsContext['request'],
response: NextServer.GetServerSidePropsContext['response']
response: NextServer.GetServerSidePropsContext['response'],
): CookieStorage.Adapter => {
const cookiesMap = { ...request.cookies };
const allCookies = Object.entries(cookiesMap).map(([name, value]) => ({
Expand All @@ -158,6 +159,7 @@ const createCookieStorageAdapterFromGetServerSidePropsContext = (
return {
get(name) {
const value = cookiesMap[ensureEncodedForJSCookie(name)];

return value
? {
name,
Expand All @@ -173,47 +175,48 @@ const createCookieStorageAdapterFromGetServerSidePropsContext = (
'Set-Cookie',
`${ensureEncodedForJSCookie(name)}=${value};${
options ? serializeSetCookieOptions(options) : ''
}`
}`,
);
},
delete(name) {
response.setHeader(
'Set-Cookie',
`${ensureEncodedForJSCookie(
name
)}=;Expires=${DATE_IN_THE_PAST.toUTCString()}`
name,
)}=;Expires=${DATE_IN_THE_PAST.toUTCString()}`,
);
},
};
};

const createMutableCookieStoreFromHeaders = (
headers: Headers
headers: Headers,
): Pick<CookieStorage.Adapter, 'set' | 'delete'> => {
const setFunc: CookieStorage.Adapter['set'] = (name, value, options) => {
headers.append(
'Set-Cookie',
`${ensureEncodedForJSCookie(name)}=${value};${
options ? serializeSetCookieOptions(options) : ''
}`
}`,
);
};
const deleteFunc: CookieStorage.Adapter['delete'] = name => {
headers.append(
'Set-Cookie',
`${ensureEncodedForJSCookie(
name
)}=;Expires=${DATE_IN_THE_PAST.toUTCString()}`
name,
)}=;Expires=${DATE_IN_THE_PAST.toUTCString()}`,
);
};

return {
set: setFunc,
delete: deleteFunc,
};
};

const serializeSetCookieOptions = (
options: CookieStorage.SetCookieOptions
options: CookieStorage.SetCookieOptions,
): string => {
const { expires, domain, httpOnly, sameSite, secure } = options;
const serializedOptions: string[] = [];
Expand All @@ -232,6 +235,7 @@ const serializeSetCookieOptions = (
if (secure) {
serializedOptions.push(`Secure`);
}

return serializedOptions.join(';');
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,10 @@ import {
runWithAmplifyServerContext as runWithAmplifyServerContextCore,
} from 'aws-amplify/adapter-core';

import { createCookieStorageAdapterFromNextServerContext } from './createCookieStorageAdapterFromNextServerContext';
import { NextServer } from '../types';

import { createCookieStorageAdapterFromNextServerContext } from './createCookieStorageAdapterFromNextServerContext';

export const createRunWithAmplifyServerContext = ({
config: resourcesConfig,
}: {
Expand All @@ -31,24 +32,24 @@ export const createRunWithAmplifyServerContext = ({
? sharedInMemoryStorage
: createKeyValueStorageFromCookieStorageAdapter(
createCookieStorageAdapterFromNextServerContext(
nextServerContext
)
nextServerContext,
),
);
const credentialsProvider = createAWSCredentialsAndIdentityIdProvider(
resourcesConfig.Auth,
keyValueStorage
keyValueStorage,
);
const tokenProvider = createUserPoolsTokenProvider(
resourcesConfig.Auth,
keyValueStorage
keyValueStorage,
);

return runWithAmplifyServerContextCore(
resourcesConfig,
{
Auth: { credentialsProvider, tokenProvider },
},
operation
operation,
);
}

Expand Down
2 changes: 1 addition & 1 deletion packages/adapter-nextjs/src/utils/getAmplifyConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { LegacyConfig } from 'aws-amplify/adapter-core';
import { parseAWSExports } from '@aws-amplify/core/internals/utils';

export const getAmplifyConfig = (
config: ResourcesConfig | LegacyConfig
config: ResourcesConfig | LegacyConfig,
): ResourcesConfig =>
Object.keys(config).some(key => key.startsWith('aws_'))
? parseAWSExports(config)
Expand Down
56 changes: 0 additions & 56 deletions packages/adapter-nextjs/tslint.json

This file was deleted.

0 comments on commit ef28a20

Please sign in to comment.