fixed: use azure function V3

This commit is contained in:
lzh
2023-12-16 00:10:21 +08:00
parent 28b324779d
commit af51db71cb
18 changed files with 1584 additions and 150 deletions
@@ -19,11 +19,6 @@ jobs:
with:
submodules: true
lfs: false
# Set up Node.js 18 for the API
- name: Set up Node.js 18 for API
uses: actions/setup-node@v3
with:
node-version: '18'
- name: Build And Deploy
id: builddeploy
@@ -35,7 +30,7 @@ jobs:
###### Repository/Build Configurations - These values can be configured to match your app requirements. ######
# For more information regarding Static Web App workflow configurations, please visit: https://aka.ms/swaworkflowconfig
app_location: "/front" # App source code path
api_location: "/front/api" # Api source code path - optional
api_location: "api" # Api source code path - optional
output_location: "dist/ng_front" # Built app content directory - optional
###### End of Repository/Build Configurations ######
+19
View File
@@ -0,0 +1,19 @@
{
"bindings": [
{
"authLevel": "anonymous",
"type": "httpTrigger",
"direction": "in",
"name": "req",
"methods": [
"get",
"post"
]
},
{
"type": "http",
"direction": "out",
"name": "res"
}
]
}
+47
View File
@@ -0,0 +1,47 @@
const { MongoClient } = require('mongodb');
const connectionString = "mongodb://games:oQ5bO7YMfpu99oZMpKs0fjjypybyIMwBHJh7TmK8FYj1J41StnByDp1vxZ0huSXxlYbNLiRtNdvZACDb9cByMQ%3D%3D@games.mongo.cosmos.azure.com:10255/?ssl=true&retrywrites=false&maxIdleTimeMS=120000&appName=@games@";
const client = new MongoClient(connectionString);
const DATABASE_NAME = "games";
const COLLECTION = "games";
module.exports = async function (context, req) {
try {
await client.connect();
const db = client.db(DATABASE_NAME);
const collection = db.collection(COLLECTION);
const body = req.body || {};
const page = body.page || 1;
const size = body.size || 10;
const original_price = body["Original Price"];
const title = body["Title"];
const developer = body.Developer;
let query_conditions = {};
if (original_price) {
query_conditions["Original Price"] = { $regex: original_price, $options: "i" };
}
if (title) {
query_conditions["Title"] = { $regex: title, $options: "i" };
}
if (developer) {
query_conditions["Developer"] = { $regex: developer, $options: "i" };
}
const data = await collection.find(query_conditions).skip((page - 1) * size).limit(size).toArray();
const total = await collection.countDocuments(query_conditions);
context.res = {
status: 200,
body: { code: 200, total: total, data: data, msg: "SUCCESS", body: query_conditions }
};
} catch (e) {
context.res = {
status: 500,
body: { code: 500, msg: e.message }
};
} finally {
if (client) {
client.close();
}
}
};
+3
View File
@@ -0,0 +1,3 @@
{
"name": "Azure"
}
+19
View File
@@ -0,0 +1,19 @@
{
"bindings": [
{
"authLevel": "anonymous",
"type": "httpTrigger",
"direction": "in",
"name": "req",
"methods": [
"get",
"post"
]
},
{
"type": "http",
"direction": "out",
"name": "res"
}
]
}
+64
View File
@@ -0,0 +1,64 @@
const { MongoClient } = require('mongodb');
const jwt = require('jsonwebtoken');
const connectionString = "mongodb://games:oQ5bO7YMfpu99oZMpKs0fjjypybyIMwBHJh7TmK8FYj1J41StnByDp1vxZ0huSXxlYbNLiRtNdvZACDb9cByMQ%3D%3D@games.mongo.cosmos.azure.com:10255/?ssl=true&retrywrites=false&maxIdleTimeMS=120000&appName=@games@";
const client = new MongoClient(connectionString);
module.exports = async function (context, req) {
context.log('JavaScript HTTP trigger function processed a request.');
if (req.method === "POST") {
// Determine if this is a login or register request
const isLogin = req.url.includes("/login");
try {
await client.connect();
const db = client.db("games");
const { username, password } = req.body;
const collection = db.collection("user");
if (isLogin) {
// Handle login
const user = await collection.findOne({ username, password });
if (user) {
const token = jwt.sign({ username }, "123456", { expiresIn: '1h' });
context.res = {
status: 200,
body: JSON.stringify({ code: 200, msg: "SUCCESS", data: { token } }),
headers: { 'Content-Type': 'application/json' }
};
} else {
context.res = {
status: 400,
body: JSON.stringify({ code: 400, msg: "Login or Registration failed" })
};
}
} else {
// Handle register
const existingUser = await collection.findOne({ username });
if (!existingUser) {
await collection.insertOne({ username, password });
context.res = {
status: 200,
body: JSON.stringify({ code: 200, msg: "SUCCESS", data: {} }),
headers: { 'Content-Type': 'application/json' }
};
} else {
context.res = {
status: 400,
body: JSON.stringify({ code: 400, msg: "Login or Registration failed" })
};
}
}
} catch (e) {
context.res = {
status: 500,
body: JSON.stringify({ code: 500, msg: e.message }),
headers: { 'Content-Type': 'application/json' }
};
} finally {
if (client) {
client.close();
}
}
}
};
+3
View File
@@ -0,0 +1,3 @@
{
"name": "Azure"
}
+1334
View File
File diff suppressed because it is too large Load Diff
+3 -4
View File
@@ -7,9 +7,8 @@
"test": "echo \"No tests yet...\""
},
"dependencies": {
"@azure/functions": "^4.1.0",
"mongodb": "^6.3.0"
"mongodb": "^4.0.0",
"jsonwebtoken": "^8.5.1"
},
"devDependencies": {},
"main": "src/functions/*.js"
"devDependencies": {}
}
+19
View File
@@ -0,0 +1,19 @@
{
"bindings": [
{
"authLevel": "anonymous",
"type": "httpTrigger",
"direction": "in",
"name": "req",
"methods": [
"get",
"post"
]
},
{
"type": "http",
"direction": "out",
"name": "res"
}
]
}
+64
View File
@@ -0,0 +1,64 @@
const { MongoClient } = require('mongodb');
const jwt = require('jsonwebtoken');
const connectionString = "mongodb://games:oQ5bO7YMfpu99oZMpKs0fjjypybyIMwBHJh7TmK8FYj1J41StnByDp1vxZ0huSXxlYbNLiRtNdvZACDb9cByMQ%3D%3D@games.mongo.cosmos.azure.com:10255/?ssl=true&retrywrites=false&maxIdleTimeMS=120000&appName=@games@";
const client = new MongoClient(connectionString);
module.exports = async function (context, req) {
context.log('JavaScript HTTP trigger function processed a request.');
if (req.method === "POST") {
// Determine if this is a login or register request
const isLogin = req.url.includes("/login");
try {
await client.connect();
const db = client.db("games");
const { username, password } = req.body;
const collection = db.collection("user");
if (isLogin) {
// Handle login
const user = await collection.findOne({ username, password });
if (user) {
const token = jwt.sign({ username }, "123456", { expiresIn: '1h' });
context.res = {
status: 200,
body: JSON.stringify({ code: 200, msg: "SUCCESS", data: { token } }),
headers: { 'Content-Type': 'application/json' }
};
} else {
context.res = {
status: 400,
body: JSON.stringify({ code: 400, msg: "Login or Registration failed" })
};
}
} else {
// Handle register
const existingUser = await collection.findOne({ username });
if (!existingUser) {
await collection.insertOne({ username, password });
context.res = {
status: 200,
body: JSON.stringify({ code: 200, msg: "SUCCESS", data: {} }),
headers: { 'Content-Type': 'application/json' }
};
} else {
context.res = {
status: 400,
body: JSON.stringify({ code: 400, msg: "Login or Registration failed" })
};
}
}
} catch (e) {
context.res = {
status: 500,
body: JSON.stringify({ code: 500, msg: e.message }),
headers: { 'Content-Type': 'application/json' }
};
} finally {
if (client) {
client.close();
}
}
}
};
+3
View File
@@ -0,0 +1,3 @@
{
"name": "Azure"
}
-54
View File
@@ -1,54 +0,0 @@
const { app } = require('@azure/functions');
const { MongoClient } = require('mongodb');
var connectionString = "mongodb://games:oQ5bO7YMfpu99oZMpKs0fjjypybyIMwBHJh7TmK8FYj1J41StnByDp1vxZ0huSXxlYbNLiRtNdvZACDb9cByMQ%3D%3D@games.mongo.cosmos.azure.com:10255/?ssl=true&retrywrites=false&maxIdleTimeMS=120000&appName=@games@";
const client = new MongoClient(connectionString);
const DATABASE_NAME = "games";
const COLLECTION = "games";
app.http('games', {
methods: ['POST'], // Only POST method is allowed
authLevel: 'anonymous',
handler: async (request, context) => {
try {
await client.connect();
const db = client.db(DATABASE_NAME);
const collection = db.collection(COLLECTION);
// Extracting data from the POST request body instead of query parameters
const body = await request.json() || {};
const page = body.page || 1;
const size = body.size || 10;
const original_price = body["Original Price"];
const title = body["Title"];
const developer = body.Developer;
let query_conditions = {};
if (original_price) {
query_conditions["Original Price"] = { $regex: original_price, $options: "i" };
}
if (title) {
query_conditions["Title"] = { $regex: title, $options: "i" };
}
if (developer) {
query_conditions["Developer"] = { $regex: developer, $options: "i" };
}
const data = await collection.find(query_conditions).skip((page - 1) * size).limit(size).toArray();
const total = await collection.countDocuments(query_conditions);
context.res = {
status: 200,
body: JSON.stringify({ code: 200, total: total, data: data, msg: "SUCCESS",body:query_conditions }),
headers: { 'Content-Type': 'application/json' }
};
} catch (e) {
context.res = {
status: 500,
body: JSON.stringify({ code: 500, msg: e.message }),
headers: { 'Content-Type': 'application/json' }
};
} finally {
if (client) {
client.close();
}
}
return context.res;
}
});
-85
View File
@@ -1,85 +0,0 @@
const { app } = require('@azure/functions');
const { MongoClient } = require('mongodb');
// import jwt
const jwt = require('jsonwebtoken');
var connectionString = "mongodb://games:oQ5bO7YMfpu99oZMpKs0fjjypybyIMwBHJh7TmK8FYj1J41StnByDp1vxZ0huSXxlYbNLiRtNdvZACDb9cByMQ%3D%3D@games.mongo.cosmos.azure.com:10255/?ssl=true&retrywrites=false&maxIdleTimeMS=120000&appName=@games@";
const client = new MongoClient(connectionString);
app.http('register', {
methods: ['POST'],
authLevel: 'anonymous',
handler: async (request, context) => {
try {
await client.connect();
const db = client.db("games");
const { username, password } = await request.json();
const existingUser = await db.collection("user").findOne({ username });
if (!existingUser) {
await db.collection("user").insertOne({ username, password });
context.res = {
status: 200, // HTTP 状态码
body: JSON.stringify({ code: 200, msg: "SUCCESS", data: { /* 返回的数据 */ } }),
headers: { 'Content-Type': 'application/json' }
};
} else {
context.res = {
status: 400, // 或其他合适的状态码
body: JSON.stringify({ code: 400, msg: "Login or Registration failed" })
};
}
} catch (e) {
context.res = {
status: 500,
body: JSON.stringify({ code: 500, msg: e.message }),
headers: { 'Content-Type': 'application/json' }
};
} finally {
if (client) {
client.close();
}
return context.res;
}
}
});
app.http('login', {
methods: ['POST'],
authLevel: 'anonymous',
handler: async (request, context) => {
try {
const { username, password } = await request.json();
await client.connect();
const db = client.db("games");
const user = await db.collection("user").findOne({ username, password });
if (user) {
const token = jwt.sign({ username }, "123456" ,{ expiresIn: '1h' });
context.res = {
status: 200, // HTTP 状态码
body: JSON.stringify({ code: 200, msg: "SUCCESS", data: { token } }),
headers: { 'Content-Type': 'application/json' }
};
} else {
context.res = {
status: 400, // 或其他合适的状态码
body: JSON.stringify({ code: 400, msg: "Login or Registration failed" })
};
}
} catch (e) {
context.res = {
status: 500,
body: JSON.stringify({ code: 500, msg: e.message }),
headers: { 'Content-Type': 'application/json' }
}
} finally {
if (client) {
client.close();
}
return context.res;
}
}
});
+5 -1
View File
@@ -11,4 +11,8 @@
当修改文件提交到github时,会自动触发部署到Azure
- Static Web Apps 静态网站部署文件:dist/ng_front
- Azure functions front/api
- CosmosDB数据库的连接字符串:`mongodb://games:oQ5bO7YMfpu99oZMpKs0fjjypybyIMwBHJh7TmK8FYj1J41StnByDp1vxZ0huSXxlYbNLiRtNdvZACDb9cByMQ%3D%3D@games.mongo.cosmos.azure.com:10255/?ssl=true&retrywrites=false&maxIdleTimeMS=120000&appName=@games@`
- CosmosDB数据库的连接字符串:`mongodb://games:oQ5bO7YMfpu99oZMpKs0fjjypybyIMwBHJh7TmK8FYj1J41StnByDp1vxZ0huSXxlYbNLiRtNdvZACDb9cByMQ%3D%3D@games.mongo.cosmos.azure.com:10255/?ssl=true&retrywrites=false&maxIdleTimeMS=120000&appName=@games@`
## 相关文档说明
- Azure Function: https://learn.microsoft.com/en-us/azure/static-web-apps/add-api?tabs=angular
- Azure Static Web Apps: https://docs.microsoft.com/en-us/azure/static-web-apps/overview?tabs=angular