Skip to content

Commit

Permalink
chore(examples): add dependent-queries & bi-direction example
Browse files Browse the repository at this point in the history
  • Loading branch information
afiiif committed Sep 26, 2023
1 parent 4e00efb commit 3500cd7
Show file tree
Hide file tree
Showing 18 changed files with 526 additions and 0 deletions.
35 changes: 35 additions & 0 deletions examples/react/bi-direction-infinite-query/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

# dependencies
/node_modules
/.pnp
.pnp.js

# testing
/coverage

# next.js
/.next/
/out/

# production
/build

# misc
.DS_Store
*.pem

# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# local env files
.env*.local

# vercel
.vercel

# typescript
*.tsbuildinfo
next-env.d.ts
36 changes: 36 additions & 0 deletions examples/react/bi-direction-infinite-query/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
This is a [Next.js](https://nextjs.org/) project bootstrapped with [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app).

## Getting Started

First, run the development server:

```bash
npm run dev
# or
yarn dev
# or
pnpm dev
# or
bun dev
```

Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.

You can start editing the page by modifying `app/page.js`. The page auto-updates as you edit the file.

This project uses [`next/font`](https://nextjs.org/docs/basic-features/font-optimization) to automatically optimize and load Inter, a custom Google Font.

## Learn More

To learn more about Next.js, take a look at the following resources:

- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.

You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js/) - your feedback and contributions are welcome!

## Deploy on Vercel

The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.

Check out our [Next.js deployment documentation](https://nextjs.org/docs/deployment) for more details.
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { NextResponse } from 'next/server';

export async function GET(request) {
const searchParams = request.nextUrl.searchParams;

const cursor = Number(searchParams.get('cursor') || 0);
const pageSize = 5;

const data = Array(pageSize)
.fill(0)
.map((_, i) => {
return {
name: 'Project ' + (i + cursor) + ` (server time: ${Date.now()})`,
id: i + cursor,
};
});

const nextId = cursor < 10 ? data[data.length - 1].id + 1 : null;
const previousId = cursor > -10 ? data[0].id - pageSize : null;

await new Promise((r) => setTimeout(r, 1000)); // Simulate delay

return NextResponse.json({ data, nextId, previousId });
}
11 changes: 11 additions & 0 deletions examples/react/bi-direction-infinite-query/app/layout.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
export const metadata = {
title: 'Dependent Queries | Floppy Disk',
};

export default function RootLayout({ children }) {
return (
<html lang="en">
<body>{children}</body>
</html>
);
}
60 changes: 60 additions & 0 deletions examples/react/bi-direction-infinite-query/app/page.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
'use client';

import { createBiDirectionQuery } from 'floppy-disk';

const fetchProjects = async (cursor) => {
const res = await fetch(`/api/projects?cursor=${cursor}`);
const resJson = await res.json();
if (res.ok) return resJson;
throw resJson;
};

const useProjectsQuery = createBiDirectionQuery(
(queryKey, { pageParam }, direction) => fetchProjects(pageParam || 0),
{
select: (response, { data = [] }, direction) => {
return direction === 'prev' ? response.data.concat(data) : data.concat(response.data);
},
getPrevPageParam: (response) => response.previousId,
getNextPageParam: (response) => response.nextId,
},
);

export default function BiDirectionPage() {
const {
data,
fetchPrevPage,
hasPrevPage,
isWaitingPrevPage,
fetchNextPage,
hasNextPage,
isWaitingNextPage,
} = useProjectsQuery();

return (
<main>
<h1>Bi-Direction Infinite Query</h1>
<button
onClick={() => {
console.log(useProjectsQuery.get());
}}
>
Check on console log
</button>
<hr />
<button onClick={fetchPrevPage}>
Prev {isWaitingPrevPage && '⏳'}
{!hasPrevPage && '🔴'}
</button>
<ul>
{data.map((item) => (
<li key={item.id}>{JSON.stringify(item)}</li>
))}
</ul>
<button onClick={fetchNextPage}>
Next {isWaitingNextPage && '⏳'}
{!hasNextPage && '🔴'}
</button>
</main>
);
}
4 changes: 4 additions & 0 deletions examples/react/bi-direction-infinite-query/next.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
/** @type {import('next').NextConfig} */
const nextConfig = {}

module.exports = nextConfig
17 changes: 17 additions & 0 deletions examples/react/bi-direction-infinite-query/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
"name": "floppy-disk-example",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"floppy-disk": "^2.6.0",
"next": "13.5.2",
"react": "18.2.0",
"react-dom": "18.2.0"
}
}
35 changes: 35 additions & 0 deletions examples/react/dependent-queries/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

# dependencies
/node_modules
/.pnp
.pnp.js

# testing
/coverage

# next.js
/.next/
/out/

# production
/build

# misc
.DS_Store
*.pem

# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# local env files
.env*.local

# vercel
.vercel

# typescript
*.tsbuildinfo
next-env.d.ts
36 changes: 36 additions & 0 deletions examples/react/dependent-queries/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
This is a [Next.js](https://nextjs.org/) project bootstrapped with [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app).

## Getting Started

First, run the development server:

```bash
npm run dev
# or
yarn dev
# or
pnpm dev
# or
bun dev
```

Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.

You can start editing the page by modifying `app/page.js`. The page auto-updates as you edit the file.

This project uses [`next/font`](https://nextjs.org/docs/basic-features/font-optimization) to automatically optimize and load Inter, a custom Google Font.

## Learn More

To learn more about Next.js, take a look at the following resources:

- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.

You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js/) - your feedback and contributions are welcome!

## Deploy on Vercel

The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.

Check out our [Next.js deployment documentation](https://nextjs.org/docs/deployment) for more details.
34 changes: 34 additions & 0 deletions examples/react/dependent-queries/app/api/cities/route.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { NextResponse } from 'next/server';

import { countries, paginate } from '../data';

export async function GET(request) {
const searchParams = request.nextUrl.searchParams;
const query = searchParams.get('q')?.toLocaleLowerCase();
const countryId = searchParams.get('countryId');
const provinceId = searchParams.get('provinceId');
if (!query || !countryId || !provinceId) {
return NextResponse.json(
{ message: 'Please provide country id, province id, & query parameter' },
{ status: 400 },
);
}

const provinces = countries.find((item) => item.id === countryId)?.provinces;
if (!provinces) {
return NextResponse.json({ message: `Country id "${countryId}" not found` }, { status: 404 });
}

const cities = provinces.find((item) => item.id === provinceId)?.cities;
if (!cities) {
return NextResponse.json({ message: `Province id "${provinceId}" not found` }, { status: 404 });
}

const { records, pagination } = paginate(
cities.filter((item) => item.name.toLocaleLowerCase().includes(query)),
);
return NextResponse.json({
records: records.map(({ id, name }) => ({ id, name })),
pagination,
});
}
19 changes: 19 additions & 0 deletions examples/react/dependent-queries/app/api/countries/route.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { NextResponse } from 'next/server';

import { countries, paginate } from '../data';

export async function GET(request) {
const searchParams = request.nextUrl.searchParams;
const query = searchParams.get('q')?.toLocaleLowerCase();
if (!query) {
return NextResponse.json({ message: 'Please provide a query parameter' }, { status: 400 });
}

const { records, pagination } = paginate(
countries.filter((item) => item.name.toLocaleLowerCase().includes(query)),
);
return NextResponse.json({
records: records.map(({ id, name }) => ({ id, name })),
pagination,
});
}
31 changes: 31 additions & 0 deletions examples/react/dependent-queries/app/api/data.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { faker } from '@faker-js/faker';

export const paginate = (data, page = 1, limit = 10) => {
return {
records: data.slice((page - 1) * limit, page * limit),
pagination: {
currentPage: page,
totalPages: Math.ceil(data.length / limit),
totalRecords: data.length,
},
};
};

export const countries = [...Array(50)].map(() => {
return {
id: faker.string.alphanumeric(8),
name: faker.lorem.words(2),
provinces: [...Array(50)].map(() => {
return {
id: faker.string.alphanumeric(8),
name: faker.lorem.words(2),
cities: [...Array(50)].map(() => {
return {
id: faker.string.alphanumeric(8),
name: faker.lorem.words(2),
};
}),
};
}),
};
});
28 changes: 28 additions & 0 deletions examples/react/dependent-queries/app/api/provinces/route.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { NextResponse } from 'next/server';

import { countries, paginate } from '../data';

export async function GET(request) {
const searchParams = request.nextUrl.searchParams;
const query = searchParams.get('q')?.toLocaleLowerCase();
const countryId = searchParams.get('countryId');
if (!query || !countryId) {
return NextResponse.json(
{ message: 'Please provide country id & query parameter' },
{ status: 400 },
);
}

const provinces = countries.find((item) => item.id === countryId)?.provinces;
if (!provinces) {
return NextResponse.json({ message: `Country id "${countryId}" not found` }, { status: 404 });
}

const { records, pagination } = paginate(
provinces.filter((item) => item.name.toLocaleLowerCase().includes(query)),
);
return NextResponse.json({
records: records.map(({ id, name }) => ({ id, name })),
pagination,
});
}
11 changes: 11 additions & 0 deletions examples/react/dependent-queries/app/layout.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
export const metadata = {
title: 'Dependent Queries | Floppy Disk',
};

export default function RootLayout({ children }) {
return (
<html lang="en">
<body>{children}</body>
</html>
);
}
Loading

1 comment on commit 3500cd7

@vercel
Copy link

@vercel vercel bot commented on 3500cd7 Sep 26, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

demo-floppy-disk – ./comparison/nextjs/with-floppy-disk

demo-floppy-disk-afiiif.vercel.app
demo-floppy-disk-git-main-afiiif.vercel.app
demo-floppy-disk.vercel.app

Please sign in to comment.