Skip to content

Commit

Permalink
first commit
Browse files Browse the repository at this point in the history
  • Loading branch information
SoraKumo001 committed Aug 15, 2023
0 parents commit 8a15564
Show file tree
Hide file tree
Showing 9 changed files with 2,358 additions and 0 deletions.
67 changes: 67 additions & 0 deletions .eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
{
"env": {
"node": true,
"es6": true,
"browser": true
},
"extends": [
"eslint:recommended",
"plugin:prettier/recommended",
"plugin:@typescript-eslint/recommended"
],
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaVersion": 6,
"sourceType": "module",
"ecmaFeatures": {
"modules": true
}
},
"plugins": [
"@typescript-eslint",
"import"
],
"rules": {
"prettier/prettier": "error",
"no-empty": 0,
"@typescript-eslint/explicit-module-boundary-types": 0,
"@typescript-eslint/no-non-null-assertion": 0,
"@typescript-eslint/no-var-requires": 0,
"import/order": [
"error",
{
"groups": [
"builtin",
"external",
"internal",
[
"parent",
"sibling"
],
"object",
"type",
"index"
],
"pathGroupsExcludedImportTypes": [
"builtin"
],
"alphabetize": {
"order": "asc",
"caseInsensitive": true
},
"pathGroups": [
{
"pattern": "@/components/common",
"group": "internal",
"position": "before"
},
{
"pattern": "@/components/hooks",
"group": "internal",
"position": "before"
}
]
}
]
}
}
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
dist
node_modules
test
8 changes: 8 additions & 0 deletions .npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
.github
/node_modules
/src
.eslintrc.json
.gitignore
tsconfig.json
yarn.lock

21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2023 SoraKumo

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
146 changes: 146 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
# @react-libraries/next-exchange-ssr

SSR on Next.js using @apollo/client's useSuspenseQuery.
To use it, simply add ApolloSSRProvider under ApolloProvider.

## Sample

- Source
<https://github.com/SoraKumo001/next-apollo-ssr>
- App
<https://next-apollo-ssr-six.vercel.app/>

### src/pages/\_app.tsx

```tsx
import type { AppType } from "next/app";
import { useState } from "react";
import { ApolloClient, ApolloProvider, InMemoryCache } from "@apollo/client";
import { ApolloSSRProvider } from "@react-libraries/apollo-ssr";

const uri = "https://graphql.anilist.co";

const App: AppType = ({ Component }) => {
const [client] = useState(
() =>
new ApolloClient({
uri,
cache: new InMemoryCache({}),
})
);
return (
<ApolloProvider client={client}>
{/* ←Add this */}
<ApolloSSRProvider>
<Component />
</ApolloSSRProvider>
</ApolloProvider>
);
};

// getInitialProps itself is not needed, but it is needed to prevent optimization of _app.tsx
// If you don't include this, it will be executed at build time and will not be called after that.
App.getInitialProps = () => ({});

export default App;
```

### src/pages/index.tsx

```tsx
import { gql, useApolloClient, useSuspenseQuery } from "@apollo/client";
import Link from "next/link";
import { useRouter } from "next/router";
import { Suspense } from "react";

// Retrieving the animation list
const QUERY = gql`
query Query($page: Int, $perPage: Int) {
Page(page: $page, perPage: $perPage) {
media {
id
title {
english
native
}
}
pageInfo {
currentPage
hasNextPage
lastPage
perPage
total
}
}
}
`;

type PageData = {
Page: {
media: {
id: number;
siteUrl: string;
title: { english: string; native: string };
}[];
pageInfo: {
currentPage: number;
hasNextPage: boolean;
lastPage: number;
perPage: number;
total: number;
};
};
};

const AnimationList = ({ page }: { page: number }) => {
const client = useApolloClient();
const { data, refetch } = useSuspenseQuery<PageData>(QUERY, {
variables: { page, perPage: 10 },
});
const { currentPage, lastPage } = data?.Page?.pageInfo ?? {};
return (
<>
<button onClick={() => refetch()}>Refetch</button>
<button onClick={() => client.resetStore()}>Reset</button>
<div>
<Link href={`/?page=${currentPage - 1}`}>
<button disabled={currentPage <= 1}>←</button>
</Link>
<Link href={`/?page=${currentPage + 1}`}>
<button disabled={currentPage >= lastPage}>→</button>
</Link>
{currentPage}/{lastPage}
</div>
{data.Page.media.map((v) => (
<div
key={v.id}
style={{
border: "solid 1px",
padding: "8px",
margin: "8px",
borderRadius: "4px",
}}
>
<div>
{v.title.english} / {v.title.native}
</div>
<a href={v.siteUrl}>{v.siteUrl}</a>
</div>
))}
</>
);
};

const Page = () => {
const router = useRouter();
const page = Number(router.query.page) || 1;

return (
<Suspense fallback={<div>Loading</div>}>
<AnimationList page={page} />
</Suspense>
);
};

export default Page;
```
34 changes: 34 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
{
"name": "@react-libraries/apollo-ssr",
"version": "0.0.1",
"main": "dist/index.js",
"license": "MIT",
"scripts": {
"build": "tsc -b",
"lint:fix": "eslint --fix && prettier -w src"
},
"publishConfig": {
"access": "public"
},
"keywords": [
"GraphQL",
"apollo",
"client",
"Next.js",
"nextjs",
"typescript",
"suspense",
"ssr"
],
"devDependencies": {
"@apollo/client": "^3.8.1",
"@types/react": "^18.2.20",
"eslint": "^8.47.0",
"eslint-config-next": "^13.4.16",
"eslint-config-prettier": "^9.0.0",
"eslint-plugin-import": "^2.28.0",
"prettier": "^2.8.8",
"react": "^18.2.0",
"typescript": "^5.1.6"
}
}
82 changes: 82 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import { ApolloClient, ObservableQuery, useApolloClient } from "@apollo/client";
import { getSuspenseCache } from "@apollo/client/react/cache";
import { InternalQueryReference } from "@apollo/client/react/cache/QueryReference";
import {
SuspenseCache,
SuspenseCacheOptions,
} from "@apollo/client/react/cache/SuspenseCache";
import { CacheKey } from "@apollo/client/react/cache/types";
import { Fragment, ReactNode, createElement, useRef } from "react";

class SSRCache extends SuspenseCache {
constructor(options: SuspenseCacheOptions = Object.create(null)) {
super(options);
}
getQueryRef<TData = any>(
cacheKey: CacheKey,
createObservable: () => ObservableQuery<TData>
) {
const ref = super.getQueryRef(cacheKey, createObservable);
this.refs.add(ref);
return ref;
}

finished = false;
refs = new Set<InternalQueryReference<any>>();
}

const DATA_NAME = "__NEXT_DATA_PROMISE__";

const DataRender = () => {
const client = useApolloClient();
const cache = getSuspenseCache(client);
if (typeof window === "undefined") {
if (!(cache instanceof SSRCache)) {
throw new Error("SSRCache missing.");
}
if (!cache.finished) {
throw Promise.allSettled(
Array.from(cache.refs.values()).map(({ promise }) => promise)
).then((v) => {
cache.finished = true;
return v;
});
}
}
return createElement("script", {
id: DATA_NAME,
type: "application/json",
dangerouslySetInnerHTML: {
__html: JSON.stringify(client.extract()).replace(/</g, "\\u003c"),
},
});
};

const useApolloCache = <T>(
client: ApolloClient<T> & {
[suspenseCacheSymbol]?: SuspenseCache;
}
) => {
const property = useRef<{ initialized?: boolean }>({}).current;
if (typeof window !== "undefined") {
if (!property.initialized) {
const node = document.getElementById(DATA_NAME);
if (node) client.restore(JSON.parse(node.innerHTML));
property.initialized = true;
}
} else {
if (!client[suspenseCacheSymbol]) {
client[suspenseCacheSymbol] = new SSRCache(
client.defaultOptions.react?.suspense
);
}
}
};

const suspenseCacheSymbol = Symbol.for("apollo.suspenseCache");

export const ApolloSSRProvider = ({ children }: { children: ReactNode }) => {
const client = useApolloClient();
useApolloCache(client);
return createElement(Fragment, {}, children, createElement(DataRender));
};
Loading

0 comments on commit 8a15564

Please sign in to comment.