feat: integrate cloud functions

This commit is contained in:
1721518185
2023-12-16 20:57:11 +08:00
parent 7a89f0d422
commit a958181920
21 changed files with 4721 additions and 11306 deletions
@@ -28,9 +28,9 @@ jobs:
action: "upload"
###### 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: "/" # App source code path
api_location: "" # Api source code path - optional
output_location: "" # Built app content directory - optional
app_location: "/frontend" # App source code path
api_location: "api" # Api source code path - optional
output_location: "dist/ng_front" # Built app content directory - optional
###### End of Repository/Build Configurations ######
close_pull_request_job:
+4
View File
@@ -47,3 +47,7 @@ testem.log
# System files
.DS_Store
Thumbs.db
# api
/api/node_modules
node_modules/
+10
View File
@@ -0,0 +1,10 @@
*.js.map
*.ts
.git*
.vscode
__azurite_db*__.json
__blobstorage__
__queuestorage__
local.settings.json
test
tsconfig.json
+99
View File
@@ -0,0 +1,99 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
# nyc test coverage
.nyc_output
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# TypeScript v1 declaration files
typings/
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variables file
.env
.env.test
# parcel-bundler cache (https://parceljs.org/)
.cache
# next.js build output
.next
# nuxt.js build output
.nuxt
# vuepress build output
.vuepress/dist
# Serverless directories
.serverless/
# FuseBox cache
.fusebox/
# DynamoDB Local files
.dynamodb/
# TypeScript output
dist
out
# Azure Functions artifacts
bin
obj
appsettings.json
local.settings.json
# Azurite artifacts
__blobstorage__
__queuestorage__
__azurite_db*__.json
+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"
}
]
}
+40
View File
@@ -0,0 +1,40 @@
const { MongoClient } = require('mongodb');
const connectionString = "mongodb://wecloud:riQjoBDxr09fnyu8yCa9FeP19Op8UNB1ZFVkxEw3a1cQy25YrPnTzHx460TWBp8vaWIm5ciDRGh6ACDbZ5nHeg==@wecloud.mongo.cosmos.azure.com:10255/?ssl=true&retrywrites=false&replicaSet=globaldb&maxIdleTimeMS=120000&appName=@wecloud@"
const client = new MongoClient(connectionString);
const collectionName = "wegame";
const dbName = "wegame";
module.exports = async function (context, req) {
try {
await client.connect();
const db = client.db(dbName);
const collection = db.collection(collectionName);
const body = req.body || {};
const page = body.page || 1;
const size = body.size || 10;
let query_conditions = {};
["Name", "Developer", "Distributer"].forEach(key => {
if (body[key]) {
query_conditions[key] = { $regex: body[key], $options: "i" };
}
});
context.log(query_conditions);
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" }
};
} catch (e) {
context.res = {
status: 500,
body: { code: 500, msg: `Error: ${e.message}` }
};
} finally {
if (client) {
client.close();
}
}
};
+3
View File
@@ -0,0 +1,3 @@
{
"name": "Azure"
}
+15
View File
@@ -0,0 +1,15 @@
{
"version": "2.0",
"logging": {
"applicationInsights": {
"samplingSettings": {
"isEnabled": true,
"excludedTypes": "Request"
}
}
},
"extensionBundle": {
"id": "Microsoft.Azure.Functions.ExtensionBundle",
"version": "[3.*, 4.0.0)"
}
}
+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"
}
]
}
+62
View File
@@ -0,0 +1,62 @@
const { MongoClient } = require('mongodb');
const jwt = require('jsonwebtoken');
const connectionString = "mongodb://wecloud:riQjoBDxr09fnyu8yCa9FeP19Op8UNB1ZFVkxEw3a1cQy25YrPnTzHx460TWBp8vaWIm5ciDRGh6ACDbZ5nHeg==@wecloud.mongo.cosmos.azure.com:10255/?ssl=true&retrywrites=false&replicaSet=globaldb&maxIdleTimeMS=120000&appName=@wecloud@"
const client = new MongoClient(connectionString);
const collectionName = "user";
const dbName = "games";
async function connectToDb() {
await client.connect();
return client.db(dbName).collection(collectionName);
}
function handleError(context, e) {
context.res = {
status: 500,
body: JSON.stringify({ code: 500, msg: e.message }),
headers: { 'Content-Type': 'application/json' }
};
}
function generateToken(username) {
return jwt.sign({ username }, "myCloud", { expiresIn: '2h' });
}
module.exports = async function (context, req) {
context.log('New user login ');
if (req.method !== "POST") {
context.res = {
status: 400,
body: JSON.stringify({ code: 400, msg: "Bad Request" }),
headers: { 'Content-Type': 'application/json' }
};
return;
}
try {
const collection = await connectToDb();
const { username, password } = req.body;
const user = await collection.findOne({ username, password });
if (user) {
const token = generateToken(username);
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" })
};
}
} catch (e) {
handleError(context, e);
} 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
+14
View File
@@ -0,0 +1,14 @@
{
"name": "api",
"version": "1.0.0",
"description": "",
"scripts": {
"start": "func start",
"test": "echo \"No tests yet...\""
},
"dependencies": {
"mongodb": "^4.0.0",
"jsonwebtoken": "^8.5.1"
},
"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"
}
]
}
+62
View File
@@ -0,0 +1,62 @@
const { MongoClient } = require('mongodb');
const connectionString = "mongodb://wecloud:riQjoBDxr09fnyu8yCa9FeP19Op8UNB1ZFVkxEw3a1cQy25YrPnTzHx460TWBp8vaWIm5ciDRGh6ACDbZ5nHeg==@wecloud.mongo.cosmos.azure.com:10255/?ssl=true&retrywrites=false&replicaSet=globaldb&maxIdleTimeMS=120000&appName=@wecloud@"
const client = new MongoClient(connectionString);
const collectionName = "user";
const dbName = "games";
async function connectToDb() {
await client.connect();
return client.db(dbName).collection(collectionName);
}
function handleError(context, e) {
context.res = {
status: 500,
body: JSON.stringify({ code: 500, msg: e.message }),
headers: { 'Content-Type': 'application/json' }
};
}
async function handleRegister(context, collection, username, password) {
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" })
};
}
}
module.exports = async function (context, req) {
context.log('New user register!');
if (req.method !== "POST") {
context.res = {
status: 400,
body: JSON.stringify({ code: 400, msg: "Bad Request" }),
headers: { 'Content-Type': 'application/json' }
};
return;
}
try {
const collection = await connectToDb();
const { username, password } = req.body;
await handleRegister(context, collection, username, password);
} catch (e) {
handleError(context, e);
} finally {
if (client) {
client.close();
}
}
};
+3
View File
@@ -0,0 +1,3 @@
{
"name": "Azure"
}
+28 -11301
View File
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -4,7 +4,7 @@ import { HttpClient, HttpHeaders } from '@angular/common/http';
providedIn: 'root',
})
export class ApiService {
_baseUrl = 'http://127.0.0.1:5000/api/wegame/';
_baseUrl = '/api/';
constructor(private httpClient: HttpClient) {}
+2944
View File
File diff suppressed because it is too large Load Diff
+36
View File
@@ -0,0 +1,36 @@
import pandas
import pymongo
uri = 'mongodb://wecloud:riQjoBDxr09fnyu8yCa9FeP19Op8UNB1ZFVkxEw3a1cQy25YrPnTzHx460TWBp8vaWIm5ciDRGh6ACDbZ5nHeg==@wecloud.mongo.cosmos.azure.com:10255/?ssl=true&retrywrites=false&replicaSet=globaldb&maxIdleTimeMS=120000&appName=@wecloud@'
client = pymongo.MongoClient(uri)
DATABASE_NAME = "wegame"
COLLECTION = "wegame"
USER_COLLECTION = "user"
DATASET_PATH = "games2.csv"
def read_dataset():
data = pandas.read_csv(DATASET_PATH, encoding='gbk')
data = data.fillna("")
data = data.to_dict(orient="records")
database = client[DATABASE_NAME]
list_data = []
for item in data:
list_data.append(item)
database[COLLECTION].insert_many(list_data)
return data
def get_db():
try:
_collection = client[DATABASE_NAME]
is_exist = _collection[COLLECTION].count()
print(f"{COLLECTION} is exist: {is_exist}")
return is_exist != 0
except Exception as e:
raise e
if __name__ == "__main__":
if not get_db():
read_dataset()
+3 -1
View File
@@ -1 +1,3 @@
## Start my azure cloud applocation
## Start my azure cloud applocation
- Test in local: `swa start frontend/dist/ng_front --api-location api`