feat: 后端初始化2
This commit is contained in:
@@ -7,5 +7,5 @@ export default withErrorBoundary(async (request: Request, _context: Context) =>
|
||||
const methodResponse = guardMethod(request, ['POST'])
|
||||
if (methodResponse) return methodResponse
|
||||
|
||||
return ok({ message: 'cart-add endpoint placeholder' })
|
||||
return ok({ message: '加入购物车接口待实现' })
|
||||
})
|
||||
|
||||
@@ -7,5 +7,5 @@ export default withErrorBoundary(async (request: Request, _context: Context) =>
|
||||
const methodResponse = guardMethod(request, ['POST'])
|
||||
if (methodResponse) return methodResponse
|
||||
|
||||
return ok({ message: 'login endpoint placeholder' })
|
||||
return ok({ message: '登录接口待实现' })
|
||||
})
|
||||
|
||||
@@ -7,5 +7,5 @@ export default withErrorBoundary(async (request: Request, _context: Context) =>
|
||||
const methodResponse = guardMethod(request, ['POST'])
|
||||
if (methodResponse) return methodResponse
|
||||
|
||||
return ok({ message: 'order-create endpoint placeholder' })
|
||||
return ok({ message: '创建订单接口待实现' })
|
||||
})
|
||||
|
||||
@@ -7,5 +7,5 @@ export default withErrorBoundary(async (request: Request, _context: Context) =>
|
||||
const methodResponse = guardMethod(request, ['POST'])
|
||||
if (methodResponse) return methodResponse
|
||||
|
||||
return ok({ message: 'order-pay endpoint placeholder' })
|
||||
return ok({ message: '订单支付接口待实现' })
|
||||
})
|
||||
|
||||
@@ -7,5 +7,5 @@ export default withErrorBoundary(async (request: Request, _context: Context) =>
|
||||
const methodResponse = guardMethod(request, ['GET'])
|
||||
if (methodResponse) return methodResponse
|
||||
|
||||
return ok({ message: 'product-detail endpoint placeholder' })
|
||||
return ok({ message: '商品详情接口待实现' })
|
||||
})
|
||||
|
||||
@@ -7,5 +7,5 @@ export default withErrorBoundary(async (request: Request, _context: Context) =>
|
||||
const methodResponse = guardMethod(request, ['GET'])
|
||||
if (methodResponse) return methodResponse
|
||||
|
||||
return ok({ message: 'product-list endpoint placeholder' })
|
||||
return ok({ message: '商品列表接口待实现' })
|
||||
})
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import type { Context } from '@netlify/functions'
|
||||
import { guardMethod } from '../utils/method.js'
|
||||
import { fail, ok } from '../utils/http.js'
|
||||
import { readJson } from '../utils/request.js'
|
||||
import { prisma } from '../utils/prisma.js'
|
||||
import { withErrorBoundary } from '../utils/handler.js'
|
||||
|
||||
type SupplierInfoRequest = {
|
||||
supplierIdentification?: string
|
||||
}
|
||||
|
||||
export default withErrorBoundary(async (request: Request, _context: Context) => {
|
||||
const methodResponse = guardMethod(request, ['POST'])
|
||||
if (methodResponse) return methodResponse
|
||||
|
||||
const body = await readJson<SupplierInfoRequest>(request)
|
||||
const supplierIdentification = String(body.supplierIdentification || '').trim().toLowerCase()
|
||||
|
||||
if (!supplierIdentification) {
|
||||
return fail('供应商唯一标识不能为空')
|
||||
}
|
||||
|
||||
const supplier = await prisma.supplierInfo.findUnique({
|
||||
where: { supplierIdentification }
|
||||
})
|
||||
|
||||
if (!supplier || supplier.deleted === 1) {
|
||||
return fail('供应商信息未配置或已停用', 404, 'SUPPLIER_NOT_CONFIGURED')
|
||||
}
|
||||
|
||||
return ok({
|
||||
id: supplier.id,
|
||||
supplierIdentification: supplier.supplierIdentification,
|
||||
supplierId: supplier.supplierId,
|
||||
supplierName: supplier.supplierName,
|
||||
clientId: supplier.clientId
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,86 @@
|
||||
import type { Context } from '@netlify/functions'
|
||||
import { guardMethod } from '../utils/method.js'
|
||||
import { fail, ok } from '../utils/http.js'
|
||||
import { readJson } from '../utils/request.js'
|
||||
import { prisma } from '../utils/prisma.js'
|
||||
import { createBridgeSignature } from '../utils/crypto.js'
|
||||
import { withErrorBoundary } from '../utils/handler.js'
|
||||
|
||||
type SupplierTokenRequest = {
|
||||
userId?: string
|
||||
supplierIdentification?: string
|
||||
}
|
||||
|
||||
type BridgeTokenResponse = {
|
||||
resultCode?: number
|
||||
message?: string
|
||||
accessToken?: string
|
||||
refreshToken?: string
|
||||
expire?: number
|
||||
refreshExpire?: number
|
||||
time?: string
|
||||
}
|
||||
|
||||
const normalizeBase = (base: string) => base.replace(/\/$/, '')
|
||||
|
||||
export default withErrorBoundary(async (request: Request, _context: Context) => {
|
||||
const methodResponse = guardMethod(request, ['POST'])
|
||||
if (methodResponse) return methodResponse
|
||||
|
||||
const body = await readJson<SupplierTokenRequest>(request)
|
||||
const userId = String(body.userId || '').trim()
|
||||
const supplierIdentification = String(body.supplierIdentification || '').trim().toLowerCase()
|
||||
|
||||
if (!userId || !supplierIdentification) {
|
||||
return fail('用户信息和供应商唯一标识不能为空')
|
||||
}
|
||||
|
||||
const supplier = await prisma.supplierInfo.findUnique({
|
||||
where: { supplierIdentification }
|
||||
})
|
||||
|
||||
if (!supplier || supplier.deleted === 1) {
|
||||
return fail('供应商信息未配置或已停用', 404, 'SUPPLIER_NOT_CONFIGURED')
|
||||
}
|
||||
|
||||
const timestamp = String(Date.now())
|
||||
const signature = createBridgeSignature(supplier.clientId, supplier.clientSecret, timestamp)
|
||||
const apiBase = normalizeBase(process.env.POINTS_MALL_OPEN_API_BASE || '')
|
||||
|
||||
if (!apiBase) {
|
||||
return fail('平台积分商城接口地址未配置', 500, 'OPEN_API_BASE_MISSING')
|
||||
}
|
||||
|
||||
const response = await fetch(`${apiBase}/connect/token`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({
|
||||
supplierId: supplier.supplierId,
|
||||
clientId: supplier.clientId,
|
||||
clientSecret: signature,
|
||||
code: '',
|
||||
timestamp
|
||||
})
|
||||
})
|
||||
|
||||
const tokenPayload = (await response.json().catch(() => ({}))) as BridgeTokenResponse
|
||||
|
||||
if (!response.ok || tokenPayload.resultCode !== 0) {
|
||||
return fail(tokenPayload.message || '获取平台授权令牌失败', 502, 'BRIDGE_TOKEN_FAILED')
|
||||
}
|
||||
|
||||
return ok({
|
||||
supplierIdentification,
|
||||
supplierId: supplier.supplierId,
|
||||
supplierName: supplier.supplierName,
|
||||
userId,
|
||||
token: tokenPayload.accessToken,
|
||||
accessToken: tokenPayload.accessToken,
|
||||
refreshToken: tokenPayload.refreshToken,
|
||||
expiresIn: tokenPayload.expire,
|
||||
refreshExpiresIn: tokenPayload.refreshExpire,
|
||||
issuedAt: tokenPayload.time
|
||||
})
|
||||
})
|
||||
@@ -7,5 +7,5 @@ export default withErrorBoundary(async (request: Request, _context: Context) =>
|
||||
const methodResponse = guardMethod(request, ['POST'])
|
||||
if (methodResponse) return methodResponse
|
||||
|
||||
return ok({ message: 'upload endpoint placeholder' })
|
||||
return ok({ message: '上传接口待实现' })
|
||||
})
|
||||
|
||||
@@ -7,5 +7,5 @@ export default withErrorBoundary(async (request: Request, _context: Context) =>
|
||||
const methodResponse = guardMethod(request, ['GET'])
|
||||
if (methodResponse) return methodResponse
|
||||
|
||||
return ok({ message: 'user-info endpoint placeholder' })
|
||||
return ok({ message: '用户信息接口待实现' })
|
||||
})
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
import CryptoJS from 'crypto-js'
|
||||
|
||||
export const sha256 = (value: string) => {
|
||||
return CryptoJS.SHA256(value).toString(CryptoJS.enc.Hex)
|
||||
}
|
||||
|
||||
export const createBridgeSignature = (clientId: string, clientSecret: string, timestamp: string) => {
|
||||
return sha256(`${clientId}${clientSecret}${timestamp}${clientSecret}`)
|
||||
}
|
||||
@@ -9,7 +9,7 @@ export const withErrorBoundary = (handler: FunctionHandler): FunctionHandler =>
|
||||
return await handler(request, context)
|
||||
} catch (error) {
|
||||
console.error(error)
|
||||
return fail('Internal server error', 500, 'INTERNAL_SERVER_ERROR')
|
||||
return fail('服务异常,请稍后再试', 500, 'INTERNAL_SERVER_ERROR')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +1,17 @@
|
||||
export type JsonBody = Record<string, unknown> | unknown[]
|
||||
|
||||
const corsHeaders = {
|
||||
'Access-Control-Allow-Origin': '*',
|
||||
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
|
||||
'Access-Control-Allow-Methods': 'GET, POST, PUT, PATCH, DELETE, OPTIONS'
|
||||
}
|
||||
|
||||
export const json = (body: JsonBody, init: ResponseInit = {}) =>
|
||||
Response.json(body, {
|
||||
...init,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...corsHeaders,
|
||||
...(init.headers || {})
|
||||
}
|
||||
})
|
||||
@@ -16,10 +23,11 @@ export const fail = (message: string, status = 400, code = 'BAD_REQUEST') =>
|
||||
|
||||
export const methodNotAllowed = (allowedMethods: string[]) =>
|
||||
json(
|
||||
{ success: false, error: { code: 'METHOD_NOT_ALLOWED', message: 'Method not allowed' } },
|
||||
{ success: false, error: { code: 'METHOD_NOT_ALLOWED', message: '请求方式不支持' } },
|
||||
{
|
||||
status: 405,
|
||||
headers: {
|
||||
...corsHeaders,
|
||||
Allow: allowedMethods.join(', ')
|
||||
}
|
||||
}
|
||||
@@ -28,9 +36,5 @@ export const methodNotAllowed = (allowedMethods: string[]) =>
|
||||
export const handleOptions = () =>
|
||||
new Response(null, {
|
||||
status: 204,
|
||||
headers: {
|
||||
'Access-Control-Allow-Origin': '*',
|
||||
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
|
||||
'Access-Control-Allow-Methods': 'GET, POST, PUT, PATCH, DELETE, OPTIONS'
|
||||
}
|
||||
headers: corsHeaders
|
||||
})
|
||||
|
||||
@@ -1,23 +1,16 @@
|
||||
import { neonConfig } from '@neondatabase/serverless'
|
||||
import { PrismaNeon } from '@prisma/adapter-neon'
|
||||
import { PrismaClient } from '@prisma/client'
|
||||
import ws from 'ws'
|
||||
|
||||
neonConfig.webSocketConstructor = ws
|
||||
|
||||
const connectionString = process.env.DATABASE_URL
|
||||
|
||||
if (!connectionString) {
|
||||
throw new Error('DATABASE_URL is required')
|
||||
throw new Error('缺少数据库连接配置 DATABASE_URL')
|
||||
}
|
||||
|
||||
const globalForPrisma = globalThis as typeof globalThis & {
|
||||
prisma?: PrismaClient
|
||||
}
|
||||
|
||||
const adapter = new PrismaNeon({ connectionString })
|
||||
|
||||
export const prisma = globalForPrisma.prisma || new PrismaClient({ adapter })
|
||||
export const prisma = globalForPrisma.prisma || new PrismaClient()
|
||||
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
globalForPrisma.prisma = prisma
|
||||
|
||||
Reference in New Issue
Block a user