Skip to content

Commit

Permalink
Merge pull request #46 from AElfProject/feature/mobile
Browse files Browse the repository at this point in the history
Feature/mobile
  • Loading branch information
yongenaelf authored Jul 17, 2024
2 parents 4e25c19 + 0b7cf4f commit 77872e0
Show file tree
Hide file tree
Showing 10 changed files with 201 additions and 13 deletions.
6 changes: 5 additions & 1 deletion .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,8 @@ APP_SECRET=
SPACE_ID=
COOKIE_PASSWORD=
COOKIE_NAME=
NEXT_PUBLIC_SITE_URL=
SITE_URL=
REDIS_HOST=
REDIS_PASSWORD=
REDIS_PORT=
NEXT_PUBLIC_SITE_URL=
23 changes: 20 additions & 3 deletions .github/workflows/github-pages.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ name: Deploy Next.js site to Pages
on:
# Runs on pushes targeting the default branch
push:
branches:
branches:
- github-pages

# Allows you to run this workflow manually from the Actions tab
Expand All @@ -26,6 +26,20 @@ concurrency:
cancel-in-progress: false

jobs:
services:
# Label used to access the service container
redis:
# Docker Hub image
image: redis
# Set health checks to wait until redis has started
options: >-
--health-cmd "redis-cli ping"
--health-interval 10s
--health-timeout 5s
--health-retries 5
ports:
# Maps port 6379 on service container to the host
- 6379:6379
# Build job
build:
runs-on: ubuntu-latest
Expand Down Expand Up @@ -74,13 +88,16 @@ jobs:
${{ runner.os }}-nextjs-${{ hashFiles('**/package-lock.json', '**/yarn.lock') }}-
- name: Install dependencies
run: ${{ steps.detect-package-manager.outputs.manager }} ${{ steps.detect-package-manager.outputs.command }}
- name: 'Create env file'
- name: "Create env file"
run: |
touch .env
echo APP_ID=${{ secrets.APP_ID }} >> .env
echo APP_SECRET=${{ secrets.APP_SECRET }} >> .env
echo SPACE_ID=${{ secrets.SPACE_ID }} >> .env
echo NEXT_PUBLIC_SITE_URL=${{ vars.SITE_URL }} >> .env
echo REDIS_HOST=redis >> .env
echo REDIS_PORT=6379 >> .env
echo REDIS_PASSWORD=${{ secrets.REDIS_PASSWORD }} >> .env
- name: Build with Next.js
run: ${{ steps.detect-package-manager.outputs.runner }} next build
- name: Upload artifact
Expand All @@ -98,4 +115,4 @@ jobs:
steps:
- name: Deploy to GitHub Pages
id: deployment
uses: actions/deploy-pages@v4
uses: actions/deploy-pages@v4
12 changes: 12 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,18 @@ Run the following command to copy the default example and replace with your own
cp .env.example .env
```

### Redis

We use Redis optimized for fast reads locally. We do not need to use Redis in the production environment because we are using static exports.

First, install Redis locally by running brew install redis.
Start the Redis service by running redis-server. You will see the Redis port number at this point.
Replace <REDIS_HOST>, <REDIS_PORT>, and <REDIS_PASSWORD> in the .env file with your local Redis host address, port number, and password, respectively.

- <REDIS_HOST>: If running on the local machine, you can use 127.0.0.1 or localhost.
- <REDIS_PORT>: The default Redis port number is 6379. If you have not changed Redis's default configuration, you can use 6379.
- <REDIS_PASSWORD>: If your Redis server has password protection enabled, use the set password. If no password is set, you can leave it blank.

### Run the development server

```bash
Expand Down
7 changes: 7 additions & 0 deletions configuration.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export default {
redis: {
host: process.env.REDIS_HOST || "",
password: process.env.REDIS_PASSWORD || "",
port: process.env.REDIS_PORT || "",
},
};
27 changes: 24 additions & 3 deletions lib/api.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,22 @@
import { getTenantAccessToken } from "@/services/get-tenant-access-token";
import { backOff } from "exponential-backoff";

import { createRedisInstance } from "./redis";
// get redis instance
const redis = createRedisInstance();
export const fetcher = async <T = any>(
url: string,
next?: NextFetchRequestConfig
): Promise<T> => {
const startTime = new Date();
let elapsedTime;
// try fetch cached data
const cached = await redis.get(url);
if (cached) {
elapsedTime = new Date().getTime() - startTime.getTime();
console.log(url, "=======yyyyyyyyyy=====", elapsedTime);
return JSON.parse(cached) as any;
}
// fetch fresh data
const tenantAccessToken = await getTenantAccessToken();
const res = await backOff(() =>
fetch(url, {
Expand All @@ -15,6 +27,15 @@ export const fetcher = async <T = any>(
next: next || { revalidate: 6000 },
})
);

return await res.json();
elapsedTime = new Date().getTime() - startTime.getTime();
console.log(url, "=======xxxxxxxxxx=====", elapsedTime);
const result = await res.json();
// cache data setting an expiry of 1 hour
// this means that the cached data will remain alive for 60 minutes
// after that, we'll get fresh data from the DB
const MAX_AGE = 60_000 * 60; // 1 hour
const EXPIRY_MS = `PX`; // milliseconds
// cache data
await redis.set(url, JSON.stringify(result), EXPIRY_MS, MAX_AGE);
return result;
};
47 changes: 47 additions & 0 deletions lib/redis.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import Redis, { RedisOptions } from "ioredis";
import configuration from "../configuration";

function getRedisConfiguration(): {
port: string;
host: string;
password: string;
} {
return configuration.redis;
}

export function createRedisInstance(config = getRedisConfiguration()) {
try {
const options: RedisOptions = {
host: config.host,
lazyConnect: true,
showFriendlyErrorStack: true,
enableAutoPipelining: true,
maxRetriesPerRequest: 0,
retryStrategy: (times: number) => {
if (times > 3) {
throw new Error(`[Redis] Could not connect after ${times} attempts`);
}

return Math.min(times * 200, 1000);
},
};

if (config.port) {
options.port = +config.port;
}

if (config.password) {
options.password = config.password;
}

const redis = new Redis(options);

redis.on("error", (error: unknown) => {
console.warn("[Redis] Error connecting", error);
});

return redis;
} catch (e) {
throw new Error(`[Redis] Could not create a Redis instance`);
}
}
5 changes: 4 additions & 1 deletion lib/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,10 @@ export async function getFileByFolderToken(folderNodes?: NodesItem[]) {
await getFileByFolderToken(child.items);
}
}
data.items = items;
if (data) {
data.items = items;
}

return data as NodesData;
}

Expand Down
83 changes: 80 additions & 3 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
"type": "module",
"scripts": {
"dev": "next dev",
"build": "rm -rf .next && next build",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
Expand All @@ -25,6 +25,7 @@
"date-fns": "^3.6.0",
"exponential-backoff": "^3.1.1",
"github-slugger": "^2.0.0",
"ioredis": "^5.4.1",
"iron-session": "^8.0.2",
"lucide-react": "^0.408.0",
"nanoid": "^5.0.7",
Expand Down
1 change: 0 additions & 1 deletion services/get-child-nodes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,5 @@ export async function getChildNodes(parentId: string) {
`https://open.larksuite.com/open-apis/wiki/v2/spaces/${process.env.SPACE_ID}/nodes?parent_node_token=${parentId}`,
{ tags: [parentId] }
);

return schema.parse(res);
}

0 comments on commit 77872e0

Please sign in to comment.