Unverified Commit 6d8b2cd3 authored by Max Proske's avatar Max Proske Committed by GitHub

Convert `api-routes-rate-limit` example to TypeScript (#38393)

Converted `api-routes-rate-limit` example to TypeScript to match Contribution docs.

- Removed dead/non-standard/typo links for "Deploy You Own ▲" and "View Source"

## Documentation / Examples

- [X] Make sure the linting passes by running `pnpm lint`
- [X] The examples guidelines are followed from [our contributing doc](https://github.com/vercel/next.js/blob/canary/contributing.md#adding-examples)
parent 87837932
...@@ -32,3 +32,6 @@ yarn-error.log* ...@@ -32,3 +32,6 @@ yarn-error.log*
# vercel # vercel
.vercel .vercel
# typescript
*.tsbuildinfo
/// <reference types="next" />
/// <reference types="next/image-types/global" />
// NOTE: This file should not be edited
// see https://nextjs.org/docs/basic-features/typescript for more information.
...@@ -6,10 +6,17 @@ ...@@ -6,10 +6,17 @@
"start": "next start" "start": "next start"
}, },
"dependencies": { "dependencies": {
"lru-cache": "^6.0.0", "lru-cache": "^7.12.0",
"next": "latest", "next": "latest",
"react": "^17.0.2", "react": "^18.2.0",
"react-dom": "^17.0.2", "react-dom": "^18.2.0",
"uuid": "^8.3.1" "uuid": "^8.3.2"
},
"devDependencies": {
"@types/node": "^18.0.3",
"@types/react": "^18.0.15",
"@types/react-dom": "^18.0.6",
"@types/uuid": "^8.3.4",
"typescript": "^4.7.4"
} }
} }
import * as uuid from 'uuid' import type { NextApiRequest, NextApiResponse } from 'next'
import { v4 as uuidv4 } from 'uuid'
import rateLimit from '../../utils/rate-limit' import rateLimit from '../../utils/rate-limit'
const limiter = rateLimit({ const limiter = rateLimit({
...@@ -6,10 +7,13 @@ const limiter = rateLimit({ ...@@ -6,10 +7,13 @@ const limiter = rateLimit({
uniqueTokenPerInterval: 500, // Max 500 users per second uniqueTokenPerInterval: 500, // Max 500 users per second
}) })
export default async function handler(req, res) { export default async function handler(
_req: NextApiRequest,
res: NextApiResponse
) {
try { try {
await limiter.check(res, 10, 'CACHE_TOKEN') // 10 requests per minute await limiter.check(res, 10, 'CACHE_TOKEN') // 10 requests per minute
res.status(200).json({ id: uuid.v4() }) res.status(200).json({ id: uuidv4() })
} catch { } catch {
res.status(429).json({ error: 'Rate limit exceeded' }) res.status(429).json({ error: 'Rate limit exceeded' })
} }
......
...@@ -2,7 +2,7 @@ import { useState } from 'react' ...@@ -2,7 +2,7 @@ import { useState } from 'react'
import styles from '../styles.module.css' import styles from '../styles.module.css'
export default function Index() { export default function Index() {
const [response, setResponse] = useState() const [response, setResponse] = useState<Record<string, unknown> | null>(null)
const makeRequest = async () => { const makeRequest = async () => {
const res = await fetch('/api/user') const res = await fetch('/api/user')
...@@ -24,29 +24,11 @@ export default function Index() { ...@@ -24,29 +24,11 @@ export default function Index() {
Functions). Functions).
</p> </p>
<button onClick={() => makeRequest()}>Make Request</button> <button onClick={() => makeRequest()}>Make Request</button>
{response && (
<code className={styles.code}> <code className={styles.code}>
<div> <pre>{JSON.stringify(response, null, 2)}</pre>
<b>Status Code: </b>
{response?.status || 'None'}
</div>
<div>
<b>Request Limit: </b>
{response?.limit || 'None'}
</div>
<div>
<b>Remaining Requests: </b>
{response?.remaining || 'None'}
</div>
<div>
<b>Body: </b>
{JSON.stringify(response?.body) || 'None'}
</div>
</code> </code>
<div className={styles.links}> )}
<a href="#">View Source</a>
{' | '}
<a href="#">Deploy You Own ▲</a>
</div>
</main> </main>
) )
} }
{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": false,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
"exclude": ["node_modules"]
}
const LRU = require('lru-cache') import type { NextApiResponse } from 'next'
import LRU from 'lru-cache'
const rateLimit = (options) => { type Options = {
uniqueTokenPerInterval?: number
interval?: number
}
export default function rateLimit(options?: Options) {
const tokenCache = new LRU({ const tokenCache = new LRU({
max: parseInt(options.uniqueTokenPerInterval || 500, 10), max: options?.uniqueTokenPerInterval || 500,
maxAge: parseInt(options.interval || 60000, 10), ttl: options?.interval || 60000,
}) })
return { return {
check: (res, limit, token) => check: (res: NextApiResponse, limit: number, token: string) =>
new Promise((resolve, reject) => { new Promise<void>((resolve, reject) => {
const tokenCount = tokenCache.get(token) || [0] const tokenCount = (tokenCache.get(token) as number[]) || [0]
if (tokenCount[0] === 0) { if (tokenCount[0] === 0) {
tokenCache.set(token, tokenCount) tokenCache.set(token, tokenCount)
} }
tokenCount[0] += 1 tokenCount[0] += 1
const currentUsage = tokenCount[0] const currentUsage = tokenCount[0]
const isRateLimited = currentUsage >= parseInt(limit, 10) const isRateLimited = currentUsage >= limit
res.setHeader('X-RateLimit-Limit', limit) res.setHeader('X-RateLimit-Limit', limit)
res.setHeader( res.setHeader(
'X-RateLimit-Remaining', 'X-RateLimit-Remaining',
...@@ -27,5 +33,3 @@ const rateLimit = (options) => { ...@@ -27,5 +33,3 @@ const rateLimit = (options) => {
}), }),
} }
} }
export default rateLimit
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment