nextjs 配置 progress 查询数据

本文最后更新于 2024年4月11日 上午

首先我们在项目里新建 src/lib/data.ts 文件,这里的是我们的业务逻辑,直接操作我们的数据 porgress数据库。

1
2
// 引入 sql 查询方法
import { sql } from '@vercel/postgres'

比如,查询一条数据,我们可以这样编写:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

export async function fetchRevenue() {
// Add noStore() here to prevent the response from being cached.
// This is equivalent to in fetch(..., {cache: 'no-store'}).

try {
// Artificially delay a response for demo purposes.
// Don't do this in production :)

// console.log('Fetching revenue data...');
// await new Promise((resolve) => setTimeout(resolve, 3000));

// 查询语句
const data = await sql<Revenue>`SELECT * FROM revenue`;

// console.log('Data fetch completed after 3 seconds.');

// 返回查询结果
return data.rows;
} catch (error) {
console.error('Database Error:', error);
throw new Error('Failed to fetch revenue data.');
}
}

我们还可以对查询到的rows数据进行我们需要格式上的处理,例如下面的代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
export async function fetchLatestInvoices() {
try {
const data = await sql<LatestInvoiceRaw>`
SELECT invoices.amount, customers.name, customers.image_url, customers.email, invoices.id
FROM invoices
JOIN customers ON invoices.customer_id = customers.id
ORDER BY invoices.date DESC
LIMIT 5`;

const latestInvoices = data.rows.map((invoice) => ({
...invoice,
amount: formatCurrency(invoice.amount),
}));
return latestInvoices;
} catch (error) {
console.error('Database Error:', error);
throw new Error('Failed to fetch the latest invoices.');
}
}

同时我们还可以对若干集合的数据进行处理,例如我们展示一个统计,代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
export async function fetchCardData() {
try {
// You can probably combine these into a single SQL query
// However, we are intentionally splitting them to demonstrate
// how to initialize multiple queries in parallel with JS.
const invoiceCountPromise = sql`SELECT COUNT(*) FROM invoices`;
const customerCountPromise = sql`SELECT COUNT(*) FROM customers`;
const invoiceStatusPromise = sql`SELECT
SUM(CASE WHEN status = 'paid' THEN amount ELSE 0 END) AS "paid",
SUM(CASE WHEN status = 'pending' THEN amount ELSE 0 END) AS "pending"
FROM invoices`;

const data = await Promise.all([
invoiceCountPromise,
customerCountPromise,
invoiceStatusPromise,
]);

const numberOfInvoices = Number(data[0].rows[0].count ?? '0');
const numberOfCustomers = Number(data[1].rows[0].count ?? '0');
const totalPaidInvoices = formatCurrency(data[2].rows[0].paid ?? '0');
const totalPendingInvoices = formatCurrency(data[2].rows[0].pending ?? '0');

return {
numberOfCustomers,
numberOfInvoices,
totalPaidInvoices,
totalPendingInvoices,
};
} catch (error) {
console.error('Database Error:', error);
throw new Error('Failed to fetch card data.');
}
}

这里我们一点需要注意📢,我们再调用 sql 这个方法查询数据的时候,记得他是一个异步的动作。我们需要配置使用 async/await 这样的语法。

1
2
3
4
export async const getTipsList() {
const result = await sql`SELECT * FROM revenue`;
return result.rows;
}

工具方法:

1
2
3
4
5
6
7
8
// util.ts
export const formatCurrency = (amount: number) => {
return (amount / 100).toLocaleString('en-US', {
style: 'currency',
currency: 'USD',
});
};

在查询函数使用 unstable_noStore, 我们在 src/app/lib/data.ts 中,每一个函数最顶部新增 noStore 如下面所示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// 导入所需包
import { unstable_noStore as noStore } from 'next/cache';

// 如下示例
export async function fetchRevenue() {
// add lines
noStore()

try {
// 查询语句
const data = await sql<Revenue>`SELECT * FROM revenue`;

// 返回查询结果
return data.rows;
} catch (error) {
throw new Error('Failed to fetch revenue data.');
}
}

查询显示效果如下图:


nextjs 配置 progress 查询数据
https://dev.dgdream.online/2024/04/06/nextjs 配置 progress 查询数据/
作者
执念
发布于
2024年4月6日
更新于
2024年4月11日
许可协议