Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: add req,res type #31

Merged
merged 4 commits into from
Sep 13, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/middlewares/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ export default class Middleware {
* Middleware for AI Network trigger call. It will filter duplicated request triggered by same transaction.
* It will pass request which is not from AI Network trigger.
* @param {Request} request - Request data
* @param {Res} amount - Response data
* @param {Res} response - Response data
* @param {NextFunction} next - Next function
* @returns Null if if request is duplicated.
*/
Expand Down
28 changes: 16 additions & 12 deletions src/modules/admin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { Request } from "express";
import ModuleBase from "./moduleBase";
import DepositService from "./service/depositService";
import UseService from "./service/useService";
import { RESPONSE_STATUS } from "../types/type";
import { RESPONSE_STATUS, request, response } from "../types/type";

export default class Admin extends ModuleBase {
private depositService: DepositService;
Expand Down Expand Up @@ -44,33 +44,37 @@ export default class Admin extends ModuleBase {
* Write response. Then change balance of requester and write history of user balance if response status is success.
* You should match this function with service trigger.
* @param {Request} request - Request data from request trigger. If req data is not from trigger function, it will throw error.
* @param {number} amount - Cost of service. Calculate it with checkCostAndBalance function.
* @param {number} cost - Cost of service. Calculate it with checkCostAndBalance function.
* @param {string} responseData - Data you want to response to requester.
* @param {RESPONSE_STATUS} status - Status of response. If status is success, it will change balance of requester and write history of user balance.
* @returns Result of transaction.
*/
async writeResponse(req:Request, amount: number, responseData: string, status: RESPONSE_STATUS ) {
const appName = req.body.valuePath[1];
const serviceName = req.body.valuePath[3];
const requesterAddress = req.body.auth.addr;
const requestKey = req.body.valuePath[5];
return await this.useService.writeResponse(status , appName, serviceName, requesterAddress, requestKey, responseData, amount);
async writeResponse(req:Request, cost: number, responseData: string, status: RESPONSE_STATUS ) {
const requestData = this.getDataFromServiceRequest(req);
const response: response = {
status,
cost,
responseData,
...requestData,
}
return await this.useService.writeResponse(response);
}
/**
* Get data from service request. You should use it only with service trigger.
* @param {Request} request - Request data from request trigger. If req data is not from trigger function, it will throw error.
* @returns Object with appName, serviceName, requesterAddress, requestKey, responseData.
* @returns RequestData type.
*/
getDataFromServiceRequest(req: Request) {
if(!req.body.valuePath[1] || !req.body.valuePath[3] || !req.body.valuePath[5] || !req.body.value.prompt) {
throw new Error("Not from service request");
}
return {
const requestData: request = {
appName: req.body.valuePath[1],
serviceName: req.body.valuePath[3],
requesterAddress: req.body.auth.addr,
requestKey: req.body.valuePath[5],
responseData: req.body.value.prompt,
requestData: req.body.value.prompt,
}
return requestData;
}
}
}
23 changes: 12 additions & 11 deletions src/modules/service/useService.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { SetOperation } from "@ainblockchain/ain-js/lib/types";
import { Path } from "../../constants";
import { HISTORY_TYPE, RESPONSE_STATUS } from "../../types/type";
import { HISTORY_TYPE, RESPONSE_STATUS, response } from "../../types/type";
import { buildSetOperation } from "../../utils/builder";
import ServiceBase from "./serviceBase";

Expand All @@ -27,20 +27,21 @@ export default class UseService extends ServiceBase{
serviceBillingConfig = billingConfig.service[serviceName];
}
const token = value.split(' ').length;
let amount = token * serviceBillingConfig.costPerToken;
if (serviceBillingConfig.minCost && amount < serviceBillingConfig.minCost) {
amount = serviceBillingConfig.minCost;
} else if (serviceBillingConfig.maxCost && amount > serviceBillingConfig.maxCost) {
amount = serviceBillingConfig.maxCost;
let cost = token * serviceBillingConfig.costPerToken;
if (serviceBillingConfig.minCost && cost < serviceBillingConfig.minCost) {
cost = serviceBillingConfig.minCost;
} else if (serviceBillingConfig.maxCost && cost > serviceBillingConfig.maxCost) {
cost = serviceBillingConfig.maxCost;
}
const balance = await this.app.getCreditBalance(appName, requesterAddress);
if (balance < amount) {
if (balance < cost) {
throw new Error("not enough balance");
}
return amount;
return cost;
}

async writeResponse(status: RESPONSE_STATUS, appName: string, serviceName: string, requesterAddress: string, requestKey: string, responseData: string, amount: number) {
async writeResponse(response: response) {
const { responseData, status, requesterAddress, requestKey, appName, serviceName, cost } = response;
const responsePath = Path.app(appName).response(serviceName, requesterAddress, requestKey);
const responseValue = {
status,
Expand All @@ -50,8 +51,8 @@ export default class UseService extends ServiceBase{
const responseOp = buildSetOperation("SET_VALUE", responsePath, responseValue);
ops.push(responseOp);
if (status === RESPONSE_STATUS.SUCCESS) {
const changeBalanceOp = await this.getChangeBalanceOp(appName, requesterAddress, 'DEC_VALUE', amount);
const writeHistoryOp = await this.getWriteHistoryOp(appName, requesterAddress, HISTORY_TYPE.USAGE, amount, requestKey);
const changeBalanceOp = await this.getChangeBalanceOp(appName, requesterAddress, 'DEC_VALUE', cost);
const writeHistoryOp = await this.getWriteHistoryOp(appName, requesterAddress, HISTORY_TYPE.USAGE, cost, requestKey);
ops.push(changeBalanceOp);
ops.push(writeHistoryOp);
}
Expand Down
22 changes: 18 additions & 4 deletions src/types/type.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,10 @@ export type setRuleParam = {
} & writeRuleConfig;

export type serviceBillingConfig = {
costPerToken: number;
minCost: number;
maxCost?: number;
responseTimeout?: number;
costPerToken: number;
minCost: number;
maxCost?: number;
responseTimeout?: number;
}

export type appBillingConfig = {
Expand Down Expand Up @@ -54,3 +54,17 @@ export enum RESPONSE_STATUS {
SUCCESS = "SUCCESS",
FAIL = "FAIL",
}

export type request = {
requestData: string,
requesterAddress: string,
requestKey: string,
serviceName: string,
appName: string,
};

export type response = request & {
responseData: string,
cost: number,
status: RESPONSE_STATUS,
}