Skip to content

Commit

Permalink
feat: middleware (#208)
Browse files Browse the repository at this point in the history
* feat: middleware
* feat: dynamicly add query params func
* feat: common params
* update: go mod tidy
* feat: batchExec
  • Loading branch information
huaxiabuluo committed May 13, 2022
1 parent 1e1f208 commit 673992e
Show file tree
Hide file tree
Showing 20 changed files with 440 additions and 345 deletions.
36 changes: 18 additions & 18 deletions app/utils/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,17 @@ import intl from 'react-intl-universal';
import { getRootStore } from '@app/stores';
import { trackEvent } from './stat';

const subErrMsgStr = [
'session expired',
'connection refused',
'broken pipe',
'an existing connection was forcibly closed',
'Token is expired',
];
export enum HttpResCode {
ErrBadRequest = 40004000,
ErrParam = 40004001,
ErrUnauthorized = 40104000,
ErrSession = 40104001,
ErrForbidden = 40304000,
ErrNotFound = 40404000,
ErrInternalServer = 50004000,
ErrNotImplemented = 50104000,
ErrUnknown = 90004000,
}

const service = axios.create({
transformResponse: [
Expand All @@ -39,24 +43,20 @@ service.interceptors.request.use(config => {

service.interceptors.response.use(
(response: any) => {
const { code, message: errMsg } = response.data;
const isConnectReq = /api-nebula\/db\/connect$/.test(response.config?.url);
// if connection refused, login again
if (code === -1 && new RegExp(subErrMsgStr.join('|')).test(errMsg)) {
message.warning(errMsg);
!isConnectReq && getRootStore().global.logout();
} else if (code === -1 && errMsg) {
message.warning(errMsg);
}
return response.data;
const isExecReq = /api-nebula\/db\/(exec|batchExec)$/.test(response.config?.url);
return isExecReq ? response.data?.data : response.data;
},
(error: any) => {
if (error.response && error.response.status) {
if (error.response?.status) {
message.error(
`${intl.get('common.requestError')}: ${error.response.status} ${
error.response.statusText
}`,
);
// relogin
if (error.response.data?.code === HttpResCode.ErrSession) {
getRootStore().global.logout();
}
return error.response;
} else {
message.error(`${intl.get('common.requestError')}: ${error}`);
Expand Down
2 changes: 1 addition & 1 deletion config/webpack.prod.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ const publicConfig = {
path: path.join(__dirname, '../dist/'),
filename: '[name].[chunkhash].js',
chunkFilename: '[name].[contenthash].js',
publicPath: '/assets/',
publicPath: '/',
},
module: {
rules: [
Expand Down
4 changes: 2 additions & 2 deletions server-v2/api/studio/etc/studio-api.yaml
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
Name: studio-api
Host: 0.0.0.0
Port: 7002
Port: 9000
MaxBytes: 1073741824
Debug:
Enable: false
Auth:
AccessSecret: "login_secret"
AccessExpire: 7200
AccessExpire: 1800
File:
UploadDir: "./upload/"

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

33 changes: 33 additions & 0 deletions server-v2/api/studio/internal/handler/gateway/disonnecthandler.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 10 additions & 0 deletions server-v2/api/studio/internal/handler/routes.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

29 changes: 29 additions & 0 deletions server-v2/api/studio/internal/logic/gateway/batchexecngqllogic.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package gateway

import (
"context"

"github.com/vesoft-inc/nebula-studio/server/api/studio/internal/service"
"github.com/vesoft-inc/nebula-studio/server/api/studio/internal/svc"
"github.com/vesoft-inc/nebula-studio/server/api/studio/internal/types"

"github.com/zeromicro/go-zero/core/logx"
)

type BatchExecNGQLLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}

func NewBatchExecNGQLLogic(ctx context.Context, svcCtx *svc.ServiceContext) BatchExecNGQLLogic {
return BatchExecNGQLLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}

func (l *BatchExecNGQLLogic) BatchExecNGQL(req types.BatchExecNGQLParams) (*types.AnyResponse, error) {
return service.NewGatewayService(l.ctx, l.svcCtx).BatchExecNGQL(&req)
}
29 changes: 29 additions & 0 deletions server-v2/api/studio/internal/logic/gateway/disonnectlogic.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package gateway

import (
"context"

"github.com/vesoft-inc/nebula-studio/server/api/studio/internal/service"
"github.com/vesoft-inc/nebula-studio/server/api/studio/internal/svc"
"github.com/vesoft-inc/nebula-studio/server/api/studio/internal/types"

"github.com/zeromicro/go-zero/core/logx"
)

type DisonnectLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}

func NewDisonnectLogic(ctx context.Context, svcCtx *svc.ServiceContext) DisonnectLogic {
return DisonnectLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}

func (l *DisonnectLogic) Disonnect(req types.DisconnectDBParams) (*types.AnyResponse, error) {
return service.NewGatewayService(l.ctx, l.svcCtx).DisconnectDB(&req)
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,5 +25,5 @@ func NewExecNGQLLogic(ctx context.Context, svcCtx *svc.ServiceContext) ExecNGQLL
}

func (l *ExecNGQLLogic) ExecNGQL(req types.ExecNGQLParams) (resp *types.AnyResponse, err error) {
return service.NewGatewayService(l.ctx, l.svcCtx).GetExec(&req)
return service.NewGatewayService(l.ctx, l.svcCtx).ExecNGQL(&req)
}
83 changes: 45 additions & 38 deletions server-v2/api/studio/internal/service/gateway.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,12 @@ package service

import (
"context"
"encoding/base64"
"fmt"
"strings"

"github.com/vesoft-inc/nebula-http-gateway/ccore/nebula/gateway/dao"
"github.com/vesoft-inc/nebula-studio/server/api/studio/internal/svc"
"github.com/vesoft-inc/nebula-studio/server/api/studio/internal/types"
"github.com/vesoft-inc/nebula-studio/server/api/studio/pkg/auth"
"github.com/vesoft-inc/nebula-studio/server/api/studio/pkg/base"
"github.com/vesoft-inc/nebula-studio/server/api/studio/pkg/ecode"

"github.com/zeromicro/go-zero/core/logx"
Expand All @@ -19,8 +17,10 @@ var _ GatewayService = (*gatewayService)(nil)

type (
GatewayService interface {
GetExec(request *types.ExecNGQLParams) (*types.AnyResponse, error)
ExecNGQL(request *types.ExecNGQLParams) (*types.AnyResponse, error)
BatchExecNGQL(request *types.BatchExecNGQLParams) (*types.AnyResponse, error)
ConnectDB(request *types.ConnectDBParams) (*types.ConnectDBResult, error)
DisconnectDB(request *types.DisconnectDBParams) (*types.AnyResponse, error)
}

gatewayService struct {
Expand All @@ -38,50 +38,57 @@ func NewGatewayService(ctx context.Context, svcCtx *svc.ServiceContext) GatewayS
}
}

func (s *gatewayService) GetExec(request *types.ExecNGQLParams) (*types.AnyResponse, error) {
return &types.AnyResponse{
Data: map[string]any{
"message": "ok",
},
func (s *gatewayService) ConnectDB(request *types.ConnectDBParams) (*types.ConnectDBResult, error) {
return &types.ConnectDBResult{
Version: string(request.NebulaVersion),
}, nil
}

func (s *gatewayService) ConnectDB(request *types.ConnectDBParams) (*types.ConnectDBResult, error) {
fmt.Println("======request999", request)
tokenSplit := strings.Split(request.Authorization, " ")
if len(tokenSplit) != 2 {
return nil, ecode.WithCode(ecode.ErrParam, nil, "invalid authorization")
func (s *gatewayService) DisconnectDB(request *types.DisconnectDBParams) (*types.AnyResponse, error) {
if request.NSID != "" {
dao.Disconnect(request.NSID)
}
return nil, nil
}

decode, err := base64.StdEncoding.DecodeString(tokenSplit[1])
func (s *gatewayService) ExecNGQL(request *types.ExecNGQLParams) (*types.AnyResponse, error) {
execute, _, err := dao.Execute(request.NSID, request.Gql, request.ParamList)
if err != nil {
return nil, ecode.WithCode(ecode.ErrParam, err)
return nil, ecode.WithCode(ecode.ErrInternalServer, err, "exec failed")
}
return &types.AnyResponse{Data: execute}, nil
}

loginInfo := strings.Split(string(decode), ":")
if len(loginInfo) < 2 {
return nil, ecode.WithCode(ecode.ErrParam, nil, "len of account is less than two")
func (s *gatewayService) BatchExecNGQL(request *types.BatchExecNGQLParams) (*types.AnyResponse, error) {
data := make([]map[string]interface{}, 0)

NSID := request.NSID
gqls := request.Gqls
paramList := request.ParamList

for _, gql := range gqls {
execute, _, err := dao.Execute(NSID, gql, make([]string, 0))
gqlRes := map[string]interface{}{"gql": gql, "data": execute}
if err != nil {
gqlRes["message"] = err.Error()
gqlRes["code"] = base.Error
} else {
gqlRes["code"] = base.Success
}
data = append(data, gqlRes)
}

username, password := loginInfo[0], loginInfo[1]
clientInfo, err := dao.Connect(request.Address, request.Port, username, password)

tokenString, err := auth.CreateToken(
&auth.AuthData{
NebulaAddress: request.Address,
Username: username,
ClientID: clientInfo.ClientID,
},
&s.svcCtx.Config,
)

fmt.Println("=====tokenString", tokenString)

if err != nil {
return nil, ecode.WithInternalServer(err, "connect db failed")
if len(paramList) > 0 {
execute, _, err := dao.Execute(NSID, "", paramList)
gqlRes := map[string]interface{}{"gql": strings.Join(paramList, "; "), "data": execute}
if err != nil {
gqlRes["message"] = err.Error()
gqlRes["code"] = base.Error
} else {
gqlRes["code"] = base.Success
}
data = append(data, gqlRes)
}

return &types.ConnectDBResult{
Version: string(clientInfo.NebulaVersion),
}, nil
return &types.AnyResponse{Data: data}, nil
}
14 changes: 13 additions & 1 deletion server-v2/api/studio/internal/types/types.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading

0 comments on commit 673992e

Please sign in to comment.