Skip to content
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

Fix test setup 1 #234

Merged
merged 12 commits into from
Jan 19, 2022
Merged
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
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion .babelrc
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"presets": [
[
"./next-babel-patched",
"next/babel",
{
"styled-jsx": {
"plugins": ["@styled-jsx/plugin-sass"]
Expand All @@ -10,6 +10,11 @@
]
],
"plugins": [
["@babel/plugin-proposal-decorators", { "legacy": true }],
// These are required to run decorators. becuase of {"loose": true}
["@babel/plugin-proposal-class-properties", { "loose": true }],
["@babel/plugin-proposal-private-property-in-object", { "loose": true }],
["@babel/plugin-proposal-private-methods", { "loose": true }],
[
"styled-components",
{
Expand Down
12 changes: 12 additions & 0 deletions .eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"extends": "next/core-web-vitals",
"rules": {
"import/no-cycle": [
"error",
{
"maxDepth": 10,
"ignoreExternal": true
}
]
}
}
2 changes: 1 addition & 1 deletion jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ module.exports = {
preset: "ts-jest",
testEnvironment: "node",
moduleNameMapper,
moduleDirectories: [".", "src", "node_modules", "tests"],
moduleDirectories: ["src", "node_modules", "tests"],
moduleFileExtensions: ["js", "json", "jsx", "node", "ts", "tsx"],
setupFilesAfterEnv: [`<rootDir>/tests/testSetup.ts`],
testMatch: ["**/**/*.test.ts"],
Expand Down
7 changes: 7 additions & 0 deletions next.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,13 @@ const nextConfig = {
use: "yaml-loader",
});

if (!options.isServer) {
config.resolve.fallback.fs = false;
config.resolve.fallback.tls = false;
config.resolve.fallback.net = false;
config.resolve.fallback.dns = false;
}

return config;
},
};
Expand Down
5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,7 @@
"client": "concurrently -k 'yarn dev'",
"dev": "yarn codegen && next",
"build": "yarn codegen && next build",
"test": "echo \"Error: no test specified\" && exit 0",
"_test": "yarn codegen && jest --runInBand",
"test": "yarn codegen && jest --runInBand",
"start": "next start",
"seed": "ts-node -r tsconfig-paths/register --transpile-only ./src/graphql/db/seed",
"type-check": "yarn tsc"
Expand Down Expand Up @@ -53,12 +52,14 @@
"reading-time": "^1.3.0",
"sass": "^1.42.1",
"sequelize": "^6.6.2",
"sequelize-typescript": "^2.1.2",
"showdown": "^1.9.1",
"sqlite3": "^5.0.2",
"styled-components": "^5.2.1",
"twig": "^1.15.4"
},
"devDependencies": {
"@babel/plugin-proposal-decorators": "^7.16.7",
"@babel/preset-env": "^7.13.15",
"@babel/preset-typescript": "^7.13.0",
"@graphql-codegen/cli": "^1.17.8",
Expand Down
1 change: 1 addition & 0 deletions src/components/file-explorer/providers/Unsplash.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ const Unsplash: React.FC<IProps> = ({ renderer }) => {
const [totalCount, setTotalCount] = useState(0);

const fetchUnsplashMedia = async () => {
if (!query) return;
// unsplash.com/page/1/query/forest
const endpoint = url + "?page=" + page + "&query=" + query;

Expand Down
4 changes: 2 additions & 2 deletions src/components/layouts/Layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ const CustomLayout = ({ children, settings }: IProps) => {
}}
width={siteConfig.sidebar_width}
>
{settings.site_logo.src ? (
{settings.site_logo?.src ? (
<Row style={{ margin: "auto", marginLeft: 0 }}>
<Logo src={settings.site_logo.src} />
</Row>
Expand All @@ -90,7 +90,7 @@ const CustomLayout = ({ children, settings }: IProps) => {
visible={visible}
>
<div className="ant-dropdown-menu-dark" style={{ height: "100%" }}>
<Logo src={settings.site_logo.src} />
<Logo src={settings.site_logo?.src} />
<Navigation stats={stats} />
<ThemeSwitcher />
</div>
Expand Down
2 changes: 1 addition & 1 deletion src/components/post/components/post.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ function Post() {

useEffect(() => {
if (post && post.__typename === "Post") {
const content = post.html_draft || post.html;
const content = post.html_draft || post.html || "";
const words = content.split(" ").length;
setCount(words);
}
Expand Down
6 changes: 3 additions & 3 deletions src/components/settings/appearance.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ const Appearance: React.FC<Props> = ({ settings, onChange }) => {
<Form.Item label="Logo">
<ImageUpload
name="Logo"
url={settings.site_logo.src}
url={settings?.site_logo?.src}
onDone={([res]) =>
onChange("site_logo", {
src: res.src,
Expand All @@ -42,7 +42,7 @@ const Appearance: React.FC<Props> = ({ settings, onChange }) => {
<Form.Item label="Favicon">
<ImageUpload
name="Favicon"
url={settings.site_favicon.src}
url={settings?.site_favicon?.src}
onDone={([res]) =>
onChange("site_favicon", {
src: res.src,
Expand All @@ -55,7 +55,7 @@ const Appearance: React.FC<Props> = ({ settings, onChange }) => {
<Form.Item label="Banner">
<ImageUpload
name="Banner"
url={settings.banner.src}
url={settings?.banner?.src}
onDone={([res]) =>
onChange("banner", {
src: res.src,
Expand Down
33 changes: 14 additions & 19 deletions src/graphql/apollo.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
import { getSession } from "next-auth/react";
import { SessionData } from "./types";
import { IncomingMessage, ServerResponse } from "http";
import { useMemo } from "react";
import { basePath } from "@/constants";
import {
Expand All @@ -11,19 +8,11 @@ import {
concat,
} from "@apollo/client";
import { publish } from "@/shared/eventBus";
import models from "./db/models";
import { NextApiRequest, NextApiResponse } from "next";

let apolloClient: ApolloClient<NormalizedCacheObject> | undefined;

export type ResolverContext = {
req?: IncomingMessage;
res?: ServerResponse;
models?: typeof models;
session?: { user: SessionData };
author_id?: number;
};

function createIsomorphLink(context: ResolverContext = {}) {
function createIsomorphLink(context) {
if (typeof window === "undefined") {
const { SchemaLink } = require("@apollo/client/link/schema");
const { schema } = require("./schema");
Expand All @@ -48,7 +37,7 @@ const saveMiddleware = new ApolloLink((operation, forward) => {
return forward(operation);
});

export function createApolloClient(context?: ResolverContext) {
export function createApolloClient(context) {
return new ApolloClient({
ssrMode: typeof window === "undefined",
link: concat(saveMiddleware, createIsomorphLink(context)),
Expand All @@ -60,20 +49,26 @@ export async function getApolloClient(
initialState: any = null,
// Pages with Next.js data fetching methods, like `getStaticProps`, can send
// a custom context which will be used by `SchemaLink` to server render pages
context?: ResolverContext,
context: { req?: NextApiRequest; res?: NextApiResponse } = {},
) {
let session;
let defaultContext = { ...context };
if (typeof window === "undefined") {
const { getResolverContext } = require("./context");
if (!context) {
console.error(
"`getApolloClient` has been called without setting a context",
);
}

const isTest = process.env.NODE_ENV === "test";
const isBuildRunning = process.env.NEXT_PHASE === "phase-production-build";
if (!isBuildRunning) session = await getSession(context);
if (!isBuildRunning && context.req && !isTest) {
const resolverContext = await getResolverContext(context.req);
defaultContext = { ...defaultContext, ...resolverContext };
}
}
const _apolloClient =
apolloClient ?? createApolloClient({ ...context, session });

const _apolloClient = apolloClient ?? createApolloClient(defaultContext);

// If your page has Next.js data fetching methods that use Apollo Client, the initial state
// get hydrated here
Expand Down
39 changes: 39 additions & 0 deletions src/graphql/context.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import MailService from "@/graphql/mail/service";
import getAuthorIdFromRequest from "@/shared/getAuthorIdFromRequest";
import { getSession } from "next-auth/react";
import connection, { models, ModelsType } from "./db/models/models";
import { SessionData } from "./types";

const mailUtils = MailService<ModelsType>(models);
const isTest = process.env.NODE_ENV === "test";

export const getResolverContext = async ({ req }) => {
const session = isTest
? null
: ((await getSession({ req })) as unknown as { user: SessionData });

let author_id = session?.user?.id;
if (!isTest && !author_id) {
author_id = await getAuthorIdFromRequest({
req,
});
}

return {
connection,
models,
mailUtils,
session,
author_id,
};
};

type Awaited<T> = T extends null | undefined
? T // special case for `null | undefined` when not in `--strictNullChecks` mode
: T extends object & { then(onfulfilled: infer F): any } // `await` only unwraps object types with a callable `then`. Non-object types are not unwrapped
? F extends (value: infer V, ...args: any) => any // if the argument to `then` is callable, extracts the first argument
? Awaited<V> // recursively unwrap the value
: never // the argument to `then` was not callable
: T; // non-object or non-thenable

export type ResolverContext = Awaited<ReturnType<typeof getResolverContext>>;
Loading