作者 yangfu

init project

正在显示 124 个修改的文件 包含 3973 行增加0 行删除
# Compiled Object codefiles, Static and Dynamic libs (Shared Objects)
*.o
*.a
*.so
# Folders
_obj
_test
# Architecture specific extensions/prefixes
*.[568vq]
[568vq].out
*.cgo1.go
*.cgo2.c
_cgo_defun.c
_cgo_gotypes.go
_cgo_export.*
_testmain.go
*.exe
*.test
.log
.idea
app.log
go.sum
lastupdate.tmp
\ No newline at end of file
... ...
FROM golang:latest
ENV APP_DIR $GOPATH/src/character-library-metadata-bastion
RUN mkdir -p $APP_DIR
WORKDIR $APP_DIR/
COPY ./pkg pkg
COPY ./conf conf
COPY ./go.mod go.mod
COPY ./go.sum go.sum
COPY ./main.go main.go
RUN ["ln","-sf","/usr/share/zoneinfo/Asia/Shanghai","/etc/localtime"]
ENV GO111MODULE on
ENV GOPROXY https://goproxy.io
RUN ["go","mod","tidy"]
RUN ["ls"]
RUN ["go","build"]
ENTRYPOINT ["./character-library-metadata-bastion"]
\ No newline at end of file
... ...
# character-library-metadata-bastion
## 源文件管理
- 文件列表 - list
- 上传 - 上传oss / 创建file
- 加载 - loadDataTable
- 编辑 - editDataTable
- 持久化 - flushDataTable
- 导出 - url
- 删除 - delete
... ...
POSTGRESQL_DB_NAME = allied_creation_dev
POSTGRESQL_HOST = 114.55.200.59
POSTGRESQL_PORT = 31543
POSTGRESQL_USER = postgres
POSTGRESQL_PASSWORD = eagle1010
DISABLE_SQL_GENERATE_COMMENT = false
SERVICE_ENV = test
HTTP_PORT = 8081
ENABLE_KAFKA_LOG11 = true
HTTPS_PORT = 8143
ALLIED_CREATION_USER_HOST = http://allied-creation-user-dev.fjmaimaimai.com
... ...
POSTGRESQL_DB_NAME = allied_creation_test
POSTGRESQL_HOST = 114.55.200.59
POSTGRESQL_PORT = 31543
POSTGRESQL_USER = postgres
POSTGRESQL_PASSWORD = eagle1010
DISABLE_SQL_GENERATE_COMMENT = false
SERVICE_ENV = test
HTTP_PORT = 8081
ENABLE_KAFKA_LOG11 = true
HTTPS_PORT = 8143
ALLIED_CREATION_USER_HOST = http://allied-creation-user-test.fjmaimaimai.com
MANUFACTURE_DEFAULT_COMPANYID = 23
MANUFACTURE_DEFAULT_ORGID = 487
MANUFACTURE_DEFAULT_WORKSHOPID = 28
... ...
-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEA45R02HLq/QHraf7VBf6QO4ca1StnmvztF5BLVU7txhKe9FD4
CLUhwharlUlPPjYFdqm9pFxynUqt15djEPhGVUEFeBpf931pVuPugNmZ/AVj0p8y
06eTNLphkrzCdBzISUN5E3PKglz3efIzq6ZK8vbns/XSQA9NRzAPTboe0KC0Flj4
YPP1X69aJiBOGClsAjG1EXQ6gxepBiL1Fq3GtpKHrQPFHffUXEkPZJz09x6RxpuU
CrtxUKdO6eKg89COo3xLXVpOZu94+csBAgvXqmADp/XCQELZRMTTEA4OIyz7yXoK
nmqceoHaeSv4nzDDMwzITFvWmZHDPHLuZwNSZwIDAQABAoIBAQDGPKf3b0rQLt7g
irEGsrLyl4JBE7kA4bao4vEsEz+9XLUHfoxAEX+hcFvwA1a6ixYBQmRGCp1v9AAw
HteVjZ6+XpAkCV102NJsdMlphaLDS/KjIjeE9KCeuoeJ6VC9EeFJKDQMRL2vBsov
eFGYAJeiwn4cXVHSqUGYc/2wqCJ1eRHJkvprDqIeZU8ND3uQ5Gz/5azezf8hBu2P
MUDseX1PzdvvElidxpHR1KsZTvGVFMMFWRcSDfQYSIB8EevMKQS2YwU9kmiCI3s3
qDEAc/Usj64oRLh3Wwh9V0H26zpn/XyQ5pzYmWtCGUpifGuAAQeFKc1jPN6fJy6a
WwLprqV5AoGBAP0k7btOXE5+hmMGcuiu3vWg0X3EOQf7MtMlsrMbqrzS4HbaaMqP
BW4hrQOLl8zB9vOYt0TuK0/+ONLlCgYiodqA8FkC7TUHcTyHUEIE3+QTrI23CY6z
AbJgnHew4jKhRvbLFHkrrIMWgRIDlIwk7HFwHLpU9tw2SsHMz6hWQjY1AoGBAOYl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EFgQUU3m/WqorSs9UgOHYm8Cd8rID
ZsswDgYDVR0PAQH/BAQDAgGGMA8GA1UdEwEB/wQFMAMBAf8wEQYDVR0gBAowCDAG
BgRVHSAAMEMGA1UdHwQ8MDowOKA2oDSGMmh0dHA6Ly9jcmwuY29tb2RvY2EuY29t
L0FBQUNlcnRpZmljYXRlU2VydmljZXMuY3JsMDQGCCsGAQUFBwEBBCgwJjAkBggr
BgEFBQcwAYYYaHR0cDovL29jc3AuY29tb2RvY2EuY29tMA0GCSqGSIb3DQEBDAUA
A4IBAQAYh1HcdCE9nIrgJ7cz0C7M7PDmy14R3iJvm3WOnnL+5Nb+qh+cli3vA0p+
rvSNb3I8QzvAP+u431yqqcau8vzY7qN7Q/aGNnwU4M309z/+3ri0ivCRlv79Q2R+
/czSAaF9ffgZGclCKxO/WIu6pKJmBHaIkU4MiRTOok3JMrO66BQavHHxW/BBC5gA
CiIDEOUMsfnNkjcZ7Tvx5Dq2+UUTJnWvu6rvP3t3O9LEApE9GQDTF1w52z97GA1F
zZOFli9d31kWTz9RvdVFGD/tSo7oBmF0Ixa1DVBzJ0RHfxBdiSprhTEUxOipakyA
vGp4z7h/jnZymQyd/teRCBaho1+V
-----END CERTIFICATE-----
... ...
apiVersion: v1
kind: Service
metadata:
name: character-library-metadata-bastion
namespace: <replace-your-k8s-namespace>
labels:
k8s-app: character-library-metadata-bastion
spec:
ports:
- name: "http"
port: 80
targetPort: 8082
selector:
k8s-app: character-library-metadata-bastion
---
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
name: character-library-metadata-bastion
namespace: <replace-your-k8s-namespace>
labels:
k8s-app: character-library-metadata-bastion
spec:
replicas: 1
template:
metadata:
labels:
k8s-app: character-library-metadata-bastion
spec:
affinity:
nodeAffinity:
preferredDuringSchedulingIgnoredDuringExecution:
- preference: {}
weight: 100
requiredDuringSchedulingIgnoredDuringExecution:
nodeSelectorTerms:
- matchExpressions:
- key: kubernetes.io/hostname
operator: In
values:
- cn-hangzhou.i-bp1djh1xn7taumbue1ze
- cn-hangzhou.i-bp1djh1xn7taumbue1zd
- cn-hangzhou.i-bp1euf5u1ph9kbhtndhb
- cn-hangzhou.i-bp1hyp5oips9cdwxxgxy
containers:
- name: character-library-metadata-bastion
image: 192.168.0.243:5000/mmm/character-library-metadata-bastion:dev
imagePullPolicy: Always
ports:
- containerPort: 8082
volumeMounts:
- mountPath: /opt/logs
name: accesslogs
env:
- name: LOG_LEVEL
value: "debug"
- name: ERROR_BASE_CODE
value: "1"
- name: ERROR_BASE_CODE_MULTIPLE
value: "1000"
volumes:
- name: accesslogs
emptyDir: {}
\ No newline at end of file
... ...
#!/bin/bash
export PATH=/root/local/bin:$PATH
kubectl -n <replace-your-k8s-namespace> get pods | grep -q character-library-metadata-bastion
if [ "$?" == "1" ];then
kubectl create -f /tmp/dev/character-library-metadata-bastion/character-library-metadata-bastion.yaml --record
kubectl -n <replace-your-k8s-namespace> get svc | grep -q character-library-metadata-bastion
if [ "$?" == "0" ];then
echo "character-library-metadata-bastion service install success!"
else
echo "character-library-metadata-bastion service install fail!"
fi
kubectl -n <replace-your-k8s-namespace> get pods | grep -q character-library-metadata-bastion
if [ "$?" == "0" ];then
echo "character-library-metadata-bastion deployment install success!"
else
echo "character-library-metadata-bastion deployment install fail!"
fi
else
kubectl delete -f /tmp/dev/character-library-metadata-bastion/character-library-metadata-bastion.yaml
kubectl -n <replace-your-k8s-namespace> get svc | grep -q character-library-metadata-bastion
while [ "$?" == "0" ]
do
kubectl -n <replace-your-k8s-namespace> get svc | grep -q character-library-metadata-bastion
done
kubectl -n <replace-your-k8s-namespace> get pods | grep -q character-library-metadata-bastion
while [ "$?" == "0" ]
do
kubectl -n <replace-your-k8s-namespace> get pods | grep -q character-library-metadata-bastion
done
kubectl create -f /tmp/dev/character-library-metadata-bastion/character-library-metadata-bastion.yaml --record
kubectl -n <replace-your-k8s-namespace> get svc | grep -q character-library-metadata-bastion
if [ "$?" == "0" ];then
echo "character-library-metadata-bastion service update success!"
else
echo "character-library-metadata-bastion service update fail!"
fi
kubectl -n <replace-your-k8s-namespace> get pods | grep -q character-library-metadata-bastion
if [ "$?" == "0" ];then
echo "character-library-metadata-bastion deployment update success!"
else
echo "character-library-metadata-bastion deployment update fail!"
fi
fi
\ No newline at end of file
... ...
version: v1
kind: HttpApi
metadata:
service: file
path: /files
endpoints:
- method: createFile
route:
post: /
- method: updateFile
route:
put: /{fileId}
- method: getFile
route:
get: /{fileId}
- method: removeFile
route:
delete: /{fileId}
- method: listFile
route:
get: /
params:
- name: offset
- name: limit
- method: loadDataTable
route:
post: /files/load-data-table
- method: editDataTable
route:
post: /files/edit-data-table
- method: flushDataTable
route:
post: /files/flush-data-table
- method: generateMainTable
route:
post: /files/generate-main-table
\ No newline at end of file
... ...
version: v1
kind: Attribute
metadata:
name: count
description: 匹配数目
type:
primitive: int64
... ...
version: v1
kind: Attribute
metadata:
name: createdAt
description: 创建时间
type:
primitive: datetime
... ...
version: v1
kind: Attribute
metadata:
name: deletedAt
description: 删除时间
type:
primitive: datetime
... ...
version: v1
kind: Attribute
metadata:
name: limit
description: 查询限制
type:
primitive: int
... ...
version: v1
kind: Attribute
metadata:
name: offset
description: 查询偏离量
type:
primitive: int
... ...
version: v1
kind: Attribute
metadata:
name: parentId
description: 父级ID
type:
primitive: int64
... ...
version: v1
kind: Attribute
metadata:
name: sort
description: 排序
type:
primitive: int
... ...
version: v1
kind: Attribute
metadata:
name: updatedAt
description: 更新时间
type:
primitive: datetime
... ...
version: v1
kind: Attribute
metadata:
name: version
description: 版本
type:
primitive: int
... ...
version: v1
kind: Attribute
metadata:
name: SQLName
description: 对应数据库名称
type:
primitive: string
... ...
version: v1
kind: Attribute
metadata:
name: SQLType
description: 对应数据库类型
type:
primitive: string
... ...
version: v1
kind: Attribute
metadata:
name: description
description: 描述
type:
primitive: string
... ...
version: v1
kind: Attribute
metadata:
name: fieldId
description: 字段Id
type:
primitive: int
... ...
version: v1
kind: Attribute
metadata:
name: flag
description: 标识 1:主表字段 2:手动添加
type:
primitive: int
... ...
version: v1
kind: Attribute
metadata:
name: index
description: 索引序号
type:
primitive: int
... ...
version: v1
kind: Attribute
metadata:
name: name
description: 名称
type:
primitive: string
... ...
version: v1
kind: Attribute
metadata:
name: fileId
description: 文件ID
type:
primitive: int
... ...
version: v1
kind: Attribute
metadata:
name: fileInfo
description: 文件信息
type:
primitive: string
... ...
version: v1
kind: Attribute
metadata:
name: fileSize
description: 文件大小
type:
primitive: int
... ...
version: v1
kind: Attribute
metadata:
name: fileType
description: 文件类型
type:
primitive: string
... ...
version: v1
kind: Attribute
metadata:
name: operator
description: 操作人
type:
primitive: string
... ...
version: v1
kind: Attribute
metadata:
name: sourceFileId
description: 源文件Id(FileType为TemporaryFile或VerifiedFile时有值)
type:
primitive: string
... ...
version: v1
kind: Attribute
metadata:
name: table
description:
type:
primitive: string
... ...
version: v1
kind: Attribute
metadata:
name: url
description: 文件地址
type:
primitive: string
... ...
version: v1
kind: Attribute
metadata:
name: content
description: 日志内容
type:
primitive: string
... ...
version: v1
kind: Attribute
metadata:
name: entry
description: 日志内容
type:
primitive: string
... ...
version: v1
kind: Attribute
metadata:
name: logId
description: 日志ID
type:
primitive: int
... ...
version: v1
kind: Attribute
metadata:
name: logType
description: 日志类型 1.校验步骤 2.常规日志
type:
primitive: int
... ...
version: v1
kind: Attribute
metadata:
name: objectName
description: 对象名称 数据表名 / 文件名
type:
primitive: string
... ...
version: v1
kind: Attribute
metadata:
name: objectType
description: 对象类型 1.主表 2.分表 3.副表 4.源文件 5.校验文件
type:
primitive: string
... ...
version: v1
kind: Attribute
metadata:
name: operationType
description: 操作类型 1.主表生成 2.主表拆分 3.数据导入 4.分表生成 5.表复制 6.编辑记录 7.文件上传 8.文件校验
type:
primitive: string
... ...
version: v1
kind: Attribute
metadata:
name: operatorName
description: 操作人名称
type:
primitive: string
... ...
version: v1
kind: Attribute
metadata:
name: sourceId
description: 源数据ID
type:
primitive: int
... ...
version: v1
kind: Attribute
metadata:
name: PK
description: 主键字段
type:
primitive: string
... ...
version: v1
kind: Attribute
metadata:
name: dataFieldIndex
description: 数据字段序号
type:
primitive: int
... ...
version: v1
kind: Attribute
metadata:
name: dataFields
description: 数据列
type:
primitive: string
... ...
version: v1
kind: Attribute
metadata:
name: manualFields
description: 手动添加的列
type:
primitive: string
... ...
version: v1
kind: Attribute
metadata:
name: tableId
description: 表Id
type:
primitive: string
... ...
version: v1
kind: Attribute
metadata:
name: tableType
description: 表类型 MainTable:主表 SideTable:副表 SubTable:分表 ExcelTable:Excel表
type:
primitive: string
... ...
version: v1
kind: Project
metadata:
name: character-library-metadata-bastion
description: 字库元数据堡垒
version: 0.0.1
repository: gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion
contact:
name: ttt
email:
\ No newline at end of file
... ...
version: v1
kind: Schema
metadata:
name: field
description: 字段
attributes:
- ref: fieldId
required: true
- ref: index
required: true
- ref: name
required: true
- ref: SQLName
required: true
- ref: SQLType
required: true
- ref: description
required: true
- ref: flag
required: true
... ...
version: v1
kind: Schema
metadata:
name: file
description: 文件
attributes:
- ref: fileId
required: true
- ref: fileType
required: true
- ref: fileInfo
required: true
- ref: sourceFileId
required: true
- ref: operator
required: true
- ref: createdAt
required: true
- ref: updatedAt
required: true
- ref: deletedAt
required: true
- ref: version
required: true
... ...
version: v1
kind: Schema
metadata:
name: fileInfo
description: 文件信息
attributes:
- ref: name
required: true
- ref: url
required: true
- ref: fileSize
required: true
... ...
version: v1
kind: Schema
metadata:
name: log
description: 日志
attributes:
- ref: logId
required: true
- ref: logType
required: true
- ref: sourceId
required: true
- ref: entry
required: true
- ref: createdAt
required: true
... ...
version: v1
kind: Schema
metadata:
name: logEntry
description: 日志内容
attributes:
- ref: objectName
required: true
- ref: objectType
required: true
- ref: operationType
required: true
- ref: content
required: true
- ref: operatorName
required: true
... ...
version: v1
kind: Schema
metadata:
name: table
description:
attributes:
- ref: tableId
required: true
- ref: tableType
required: true
- ref: name
required: true
- ref: SQLName
required: true
- ref: parentId
required: true
- ref: dataFieldIndex
required: true
- ref: PK
required: true
- ref: dataFields
required: true
- ref: manualFields
required: true
- ref: createdAt
required: true
- ref: updatedAt
required: true
- ref: deletedAt
required: true
- ref: version
required: true
... ...
version: v1
kind: Method
metadata:
name: createFile
type: command
description: 创建文件服务
payload:
- ref: name
required: true
- ref: url
required: true
- ref: fileSize
required: true
result:
- name: file
type:
schema: file
required: true
... ...
version: v1
kind: Method
metadata:
name: editDataTable
type: command
description: 编辑表格数据
payload:
- ref: fileId
required: true
result:
- name: file
type:
schema: file
required: true
... ...
version: v1
kind: Method
metadata:
name: flushDataTable
type: command
description: 持久化表格数据
payload:
- ref: fileId
required: true
result:
- name: file
type:
schema: file
required: true
... ...
version: v1
kind: Method
metadata:
name: generateMainTable
type: command
description: 生成主表
payload:
- ref: fileId
required: true
result:
- name: file
type:
schema: file
required: true
... ...
version: v1
kind: Method
metadata:
name: getFile
type: query
description: 返回文件服务
payload:
- ref: fileId
required: true
result:
- name: file
type:
schema: file
required: true
... ...
version: v1
kind: Method
metadata:
name: listFile
type: query
description: 返回文件服务列表
payload:
- ref: offset
required: true
- ref: limit
required: true
result:
- ref: count
required: true
- name: files
type:
array: file
required: true
... ...
version: v1
kind: Method
metadata:
name: loadDataTable
type: command
description: 加载表格数据
payload:
- ref: fileId
required: true
result:
- name: file
type:
schema: file
required: true
... ...
version: v1
kind: Method
metadata:
name: removeFile
type: command
description: 移除文件服务
payload:
- ref: fileId
required: true
result:
- name: file
type:
schema: file
required: true
... ...
version: v1
kind: Method
metadata:
name: updateFile
type: command
description: 更新文件服务
payload:
- ref: fileId
required: true
result:
- name: file
type:
schema: file
required: true
... ...
version: v1
kind: Service
metadata:
name: file
description: 文件服务
... ...
swagger: "2.0"
info:
title: ""
description: 字库元数据堡垒
contact:
name: ttt
email: ""
home: ""
version: 0.0.1
consumes:
- application/json
- application/xml
produces:
- application/json
- application/xml
paths:
/files:
get:
tags:
- file
summary: 返回文件服务列表
description: 返回文件服务列表
operationId: file#listFile
parameters:
- name: offset
in: query
description: 查询偏离量
required: false
type: integer
- name: limit
in: query
description: 查询限制
required: false
type: integer
responses:
"200":
description: OK response.
schema:
$ref: '#/definitions/FileListFileResponseBody'
schemes:
- http
post:
tags:
- file
summary: 创建文件服务
description: 创建文件服务
operationId: file#createFile
parameters:
- name: CreateFileRequestBody
in: body
required: true
schema:
$ref: '#/definitions/FileCreateFileRequestBody'
responses:
"200":
description: OK response.
schema:
$ref: '#/definitions/FileCreateFileResponseBody'
schemes:
- http
/files/{fileId}:
get:
tags:
- file
summary: 返回文件服务
description: 返回文件服务
operationId: file#getFile
parameters:
- name: fileId
in: path
description: 文件ID
required: true
type: integer
responses:
"200":
description: OK response.
schema:
$ref: '#/definitions/FileGetFileResponseBody'
schemes:
- http
put:
tags:
- file
summary: 更新文件服务
description: 更新文件服务
operationId: file#updateFile
parameters:
- name: fileId
in: path
description: 文件ID
required: true
type: integer
responses:
"200":
description: OK response.
schema:
$ref: '#/definitions/FileUpdateFileResponseBody'
schemes:
- http
delete:
tags:
- file
summary: 移除文件服务
description: 移除文件服务
operationId: file#removeFile
parameters:
- name: fileId
in: path
description: 文件ID
required: true
type: integer
responses:
"200":
description: OK response.
schema:
$ref: '#/definitions/FileRemoveFileResponseBody'
schemes:
- http
/files/files/edit-data-table:
post:
tags:
- file
summary: 编辑表格数据
description: 编辑表格数据
operationId: file#editDataTable
parameters:
- name: EditDataTableRequestBody
in: body
required: true
schema:
$ref: '#/definitions/FileEditDataTableRequestBody'
responses:
"200":
description: OK response.
schema:
$ref: '#/definitions/FileEditDataTableResponseBody'
schemes:
- http
/files/files/flush-data-table:
post:
tags:
- file
summary: 持久化表格数据
description: 持久化表格数据
operationId: file#flushDataTable
parameters:
- name: FlushDataTableRequestBody
in: body
required: true
schema:
$ref: '#/definitions/FileFlushDataTableRequestBody'
responses:
"200":
description: OK response.
schema:
$ref: '#/definitions/FileFlushDataTableResponseBody'
schemes:
- http
/files/files/generate-main-table:
post:
tags:
- file
summary: 生成主表
description: 生成主表
operationId: file#generateMainTable
parameters:
- name: GenerateMainTableRequestBody
in: body
required: true
schema:
$ref: '#/definitions/FileGenerateMainTableRequestBody'
responses:
"200":
description: OK response.
schema:
$ref: '#/definitions/FileGenerateMainTableResponseBody'
schemes:
- http
/files/files/load-data-table:
post:
tags:
- file
summary: 加载表格数据
description: 加载表格数据
operationId: file#loadDataTable
parameters:
- name: LoadDataTableRequestBody
in: body
required: true
schema:
$ref: '#/definitions/FileLoadDataTableRequestBody'
responses:
"200":
description: OK response.
schema:
$ref: '#/definitions/FileLoadDataTableResponseBody'
schemes:
- http
definitions:
FileCreateFileRequestBody:
title: FileCreateFileRequestBody
type: object
properties:
fileSize:
type: integer
description: 文件大小
required:
- fileSize
name:
type: string
description: 名称
required:
- name
url:
type: string
description: 文件地址
required:
- url
FileCreateFileResponseBody:
title: 'Mediatype identifier: FileCreateFileResponseBody'
type: object
properties:
file:
$ref: '#/definitions/fileResponseBody'
FileEditDataTableRequestBody:
title: FileEditDataTableRequestBody
type: object
properties:
fileId:
type: integer
description: 文件ID
required:
- fileId
FileEditDataTableResponseBody:
title: 'Mediatype identifier: FileEditDataTableResponseBody'
type: object
properties:
file:
$ref: '#/definitions/fileResponseBody'
FileFlushDataTableRequestBody:
title: FileFlushDataTableRequestBody
type: object
properties:
fileId:
type: integer
description: 文件ID
required:
- fileId
FileFlushDataTableResponseBody:
title: 'Mediatype identifier: FileFlushDataTableResponseBody'
type: object
properties:
file:
$ref: '#/definitions/fileResponseBody'
FileGenerateMainTableRequestBody:
title: FileGenerateMainTableRequestBody
type: object
properties:
fileId:
type: integer
description: 文件ID
required:
- fileId
FileGenerateMainTableResponseBody:
title: 'Mediatype identifier: FileGenerateMainTableResponseBody'
type: object
properties:
file:
$ref: '#/definitions/fileResponseBody'
FileGetFileResponseBody:
title: 'Mediatype identifier: FileGetFileResponseBody'
type: object
properties:
file:
$ref: '#/definitions/fileResponseBody'
FileListFileResponseBody:
title: 'Mediatype identifier: FileListFileResponseBody'
type: object
properties:
count:
type: integer
description: 匹配数目
required:
- count
files:
type: array
items:
$ref: '#/definitions/fileResponseBody'
required:
- files
FileLoadDataTableRequestBody:
title: FileLoadDataTableRequestBody
type: object
properties:
fileId:
type: integer
description: 文件ID
required:
- fileId
FileLoadDataTableResponseBody:
title: 'Mediatype identifier: FileLoadDataTableResponseBody'
type: object
properties:
file:
$ref: '#/definitions/fileResponseBody'
FileRemoveFileResponseBody:
title: 'Mediatype identifier: FileRemoveFileResponseBody'
type: object
properties:
file:
$ref: '#/definitions/fileResponseBody'
FileUpdateFileResponseBody:
title: 'Mediatype identifier: FileUpdateFileResponseBody'
type: object
properties:
file:
$ref: '#/definitions/fileResponseBody'
fileResponseBody:
title: fileResponseBody
type: object
properties:
createdAt:
type: string
description: 创建时间
required:
- createdAt
deletedAt:
type: string
description: 删除时间
required:
- deletedAt
fileId:
type: integer
description: 文件ID
required:
- fileId
fileInfo:
type: string
description: 文件信息
required:
- fileInfo
fileType:
type: string
description: 文件类型
required:
- fileType
operator:
type: string
description: 操作人
required:
- operator
sourceFileId:
type: string
description: 源文件Id(FileType为TemporaryFile或VerifiedFile时有值)
required:
- sourceFileId
updatedAt:
type: string
description: 更新时间
required:
- updatedAt
version:
type: integer
description: 版本
required:
- version
description: 文件
... ...
module gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion
go 1.16
require (
github.com/Shopify/sarama v1.25.0
github.com/ajg/form v1.5.1 // indirect
github.com/beego/beego/v2 v2.0.1
github.com/fasthttp-contrib/websocket v0.0.0-20160511215533-1f3b11f56072 // indirect
github.com/fatih/structs v1.1.0 // indirect
github.com/gavv/httpexpect v2.0.0+incompatible
github.com/go-pg/pg/v10 v10.9.0
github.com/go-redis/redis v6.15.9+incompatible // indirect
github.com/go-redis/redis/v7 v7.4.1 // indirect
github.com/golang/snappy v0.0.3 // indirect
github.com/google/go-cmp v0.5.6 // indirect
github.com/google/go-querystring v1.1.0 // indirect
github.com/google/uuid v1.3.0 // indirect
github.com/imkira/go-interpol v1.1.0 // indirect
github.com/linmadan/egglib-go v0.0.0-20210313060205-8b5e456b11f7
github.com/moul/http2curl v1.0.0 // indirect
github.com/onsi/ginkgo v1.15.2
github.com/onsi/gomega v1.11.0
github.com/sergi/go-diff v1.2.0 // indirect
github.com/smartystreets/goconvey v1.7.2 // indirect
github.com/valyala/fasthttp v1.38.0 // indirect
github.com/xeipuuv/gojsonschema v1.2.0 // indirect
github.com/yalp/jsonpath v0.0.0-20180802001716-5cc68e5049a0 // indirect
github.com/yudai/gojsondiff v1.0.0 // indirect
github.com/yudai/golcs v0.0.0-20170316035057-ecda9a501e82 // indirect
github.com/yudai/pp v2.0.1+incompatible // indirect
)
replace github.com/linmadan/egglib-go v0.0.0-20210313060205-8b5e456b11f7 => github.com/tiptok/egglib-go v0.0.0-20220421085958-9682d0ac42c1
... ...
package main
import (
"fmt"
"github.com/beego/beego/v2/server/web"
"gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/constant"
"gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/infrastructure/redis"
"gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/log"
"time"
_ "gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/constant"
_ "gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/infrastructure/pg"
_ "gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/infrastructure/redis"
_ "gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/log"
_ "gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/port/beego"
)
func main() {
defer func() {
if r := recover(); r != nil {
log.Logger.Error(fmt.Sprintf("%v", r))
}
}()
log.InitLogHook(constant.ENABLE_KAFKA_LOG, true)
redis.InitRedis()
time.Sleep(time.Second)
log.Logger.Info("server start!")
web.Run()
log.Logger.Info("server stop!")
}
... ...
package factory
import (
"github.com/linmadan/egglib-go/transaction/pg"
"gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/infrastructure/repository"
)
func CreateTableRepository(options map[string]interface{}) (domain.TableRepository, error) {
var transactionContext *pg.TransactionContext
if value, ok := options["transactionContext"]; ok {
transactionContext = value.(*pg.TransactionContext)
}
return repository.NewTableRepository(transactionContext)
}
func CreateLogRepository(options map[string]interface{}) (domain.LogRepository, error) {
var transactionContext *pg.TransactionContext
if value, ok := options["transactionContext"]; ok {
transactionContext = value.(*pg.TransactionContext)
}
return repository.NewLogRepository(transactionContext)
}
func CreateFileRepository(options map[string]interface{}) (domain.FileRepository, error) {
var transactionContext *pg.TransactionContext
if value, ok := options["transactionContext"]; ok {
transactionContext = value.(*pg.TransactionContext)
}
return repository.NewFileRepository(transactionContext)
}
... ...
package factory
import (
"github.com/linmadan/egglib-go/core/application"
pG "github.com/linmadan/egglib-go/transaction/pg"
"gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/infrastructure/pg"
)
func CreateTransactionContext(options map[string]interface{}) (application.TransactionContext, error) {
return pG.NewPGTransactionContext(pg.DB), nil
}
... ...
package command
import (
"fmt"
"reflect"
"strings"
"github.com/beego/beego/v2/core/validation"
)
type CreateFileCommand struct {
// 名称
Name string `cname:"名称" json:"name" valid:"Required"`
// 文件地址
Url string `cname:"文件地址" json:"url" valid:"Required"`
// 文件大小
FileSize int `cname:"文件大小" json:"fileSize" valid:"Required"`
}
func (createFileCommand *CreateFileCommand) Valid(validation *validation.Validation) {
validation.SetError("CustomValid", "未实现的自定义认证")
}
func (createFileCommand *CreateFileCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(createFileCommand)
if err != nil {
return err
}
if !b {
elem := reflect.TypeOf(createFileCommand).Elem()
for _, validErr := range valid.Errors {
field, isExist := elem.FieldByName(validErr.Field)
if isExist {
return fmt.Errorf(strings.Replace(validErr.Message, validErr.Field, field.Tag.Get("cname"), -1))
} else {
return fmt.Errorf(validErr.Message)
}
}
}
return nil
}
... ...
package command
import (
"fmt"
"reflect"
"strings"
"github.com/beego/beego/v2/core/validation"
)
type EditDataTableCommand struct {
// 文件ID
FileId int `cname:"文件ID" json:"fileId" valid:"Required"`
}
func (editDataTableCommand *EditDataTableCommand) Valid(validation *validation.Validation) {
validation.SetError("CustomValid", "未实现的自定义认证")
}
func (editDataTableCommand *EditDataTableCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(editDataTableCommand)
if err != nil {
return err
}
if !b {
elem := reflect.TypeOf(editDataTableCommand).Elem()
for _, validErr := range valid.Errors {
field, isExist := elem.FieldByName(validErr.Field)
if isExist {
return fmt.Errorf(strings.Replace(validErr.Message, validErr.Field, field.Tag.Get("cname"), -1))
} else {
return fmt.Errorf(validErr.Message)
}
}
}
return nil
}
... ...
package command
import (
"fmt"
"reflect"
"strings"
"github.com/beego/beego/v2/core/validation"
)
type FlushDataTableCommand struct {
// 文件ID
FileId int `cname:"文件ID" json:"fileId" valid:"Required"`
}
func (flushDataTableCommand *FlushDataTableCommand) Valid(validation *validation.Validation) {
validation.SetError("CustomValid", "未实现的自定义认证")
}
func (flushDataTableCommand *FlushDataTableCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(flushDataTableCommand)
if err != nil {
return err
}
if !b {
elem := reflect.TypeOf(flushDataTableCommand).Elem()
for _, validErr := range valid.Errors {
field, isExist := elem.FieldByName(validErr.Field)
if isExist {
return fmt.Errorf(strings.Replace(validErr.Message, validErr.Field, field.Tag.Get("cname"), -1))
} else {
return fmt.Errorf(validErr.Message)
}
}
}
return nil
}
... ...
package command
import (
"fmt"
"reflect"
"strings"
"github.com/beego/beego/v2/core/validation"
)
type GenerateMainTableCommand struct {
// 文件ID
FileId int `cname:"文件ID" json:"fileId" valid:"Required"`
}
func (generateMainTableCommand *GenerateMainTableCommand) Valid(validation *validation.Validation) {
validation.SetError("CustomValid", "未实现的自定义认证")
}
func (generateMainTableCommand *GenerateMainTableCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(generateMainTableCommand)
if err != nil {
return err
}
if !b {
elem := reflect.TypeOf(generateMainTableCommand).Elem()
for _, validErr := range valid.Errors {
field, isExist := elem.FieldByName(validErr.Field)
if isExist {
return fmt.Errorf(strings.Replace(validErr.Message, validErr.Field, field.Tag.Get("cname"), -1))
} else {
return fmt.Errorf(validErr.Message)
}
}
}
return nil
}
... ...
package command
import (
"fmt"
"reflect"
"strings"
"github.com/beego/beego/v2/core/validation"
)
type LoadDataTableCommand struct {
// 文件ID
FileId int `cname:"文件ID" json:"fileId" valid:"Required"`
}
func (loadDataTableCommand *LoadDataTableCommand) Valid(validation *validation.Validation) {
validation.SetError("CustomValid", "未实现的自定义认证")
}
func (loadDataTableCommand *LoadDataTableCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(loadDataTableCommand)
if err != nil {
return err
}
if !b {
elem := reflect.TypeOf(loadDataTableCommand).Elem()
for _, validErr := range valid.Errors {
field, isExist := elem.FieldByName(validErr.Field)
if isExist {
return fmt.Errorf(strings.Replace(validErr.Message, validErr.Field, field.Tag.Get("cname"), -1))
} else {
return fmt.Errorf(validErr.Message)
}
}
}
return nil
}
... ...
package command
import (
"fmt"
"reflect"
"strings"
"github.com/beego/beego/v2/core/validation"
)
type RemoveFileCommand struct {
// 文件ID
FileId int `cname:"文件ID" json:"fileId" valid:"Required"`
}
func (removeFileCommand *RemoveFileCommand) Valid(validation *validation.Validation) {
validation.SetError("CustomValid", "未实现的自定义认证")
}
func (removeFileCommand *RemoveFileCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(removeFileCommand)
if err != nil {
return err
}
if !b {
elem := reflect.TypeOf(removeFileCommand).Elem()
for _, validErr := range valid.Errors {
field, isExist := elem.FieldByName(validErr.Field)
if isExist {
return fmt.Errorf(strings.Replace(validErr.Message, validErr.Field, field.Tag.Get("cname"), -1))
} else {
return fmt.Errorf(validErr.Message)
}
}
}
return nil
}
... ...
package command
import (
"fmt"
"reflect"
"strings"
"github.com/beego/beego/v2/core/validation"
)
type UpdateFileCommand struct {
// 文件ID
FileId int `cname:"文件ID" json:"fileId" valid:"Required"`
}
func (updateFileCommand *UpdateFileCommand) Valid(validation *validation.Validation) {
validation.SetError("CustomValid", "未实现的自定义认证")
}
func (updateFileCommand *UpdateFileCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(updateFileCommand)
if err != nil {
return err
}
if !b {
elem := reflect.TypeOf(updateFileCommand).Elem()
for _, validErr := range valid.Errors {
field, isExist := elem.FieldByName(validErr.Field)
if isExist {
return fmt.Errorf(strings.Replace(validErr.Message, validErr.Field, field.Tag.Get("cname"), -1))
} else {
return fmt.Errorf(validErr.Message)
}
}
}
return nil
}
... ...
package query
import (
"fmt"
"reflect"
"strings"
"github.com/beego/beego/v2/core/validation"
)
type GetFileQuery struct {
// 文件ID
FileId int `cname:"文件ID" json:"fileId" valid:"Required"`
}
func (getFileQuery *GetFileQuery) Valid(validation *validation.Validation) {
validation.SetError("CustomValid", "未实现的自定义认证")
}
func (getFileQuery *GetFileQuery) ValidateQuery() error {
valid := validation.Validation{}
b, err := valid.Valid(getFileQuery)
if err != nil {
return err
}
if !b {
elem := reflect.TypeOf(getFileQuery).Elem()
for _, validErr := range valid.Errors {
field, isExist := elem.FieldByName(validErr.Field)
if isExist {
return fmt.Errorf(strings.Replace(validErr.Message, validErr.Field, field.Tag.Get("cname"), -1))
} else {
return fmt.Errorf(validErr.Message)
}
}
}
return nil
}
... ...
package query
import (
"fmt"
"reflect"
"strings"
"github.com/beego/beego/v2/core/validation"
)
type ListFileQuery struct {
// 查询偏离量
Offset int `cname:"查询偏离量" json:"offset" valid:"Required"`
// 查询限制
Limit int `cname:"查询限制" json:"limit" valid:"Required"`
}
func (listFileQuery *ListFileQuery) Valid(validation *validation.Validation) {
validation.SetError("CustomValid", "未实现的自定义认证")
}
func (listFileQuery *ListFileQuery) ValidateQuery() error {
valid := validation.Validation{}
b, err := valid.Valid(listFileQuery)
if err != nil {
return err
}
if !b {
elem := reflect.TypeOf(listFileQuery).Elem()
for _, validErr := range valid.Errors {
field, isExist := elem.FieldByName(validErr.Field)
if isExist {
return fmt.Errorf(strings.Replace(validErr.Message, validErr.Field, field.Tag.Get("cname"), -1))
} else {
return fmt.Errorf(validErr.Message)
}
}
}
return nil
}
... ...
package service
import (
"fmt"
"github.com/linmadan/egglib-go/core/application"
"github.com/linmadan/egglib-go/utils/tool_funs"
"gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/application/factory"
"gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/application/file/command"
"gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/application/file/query"
"gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/domain"
)
// 文件服务
type FileService struct {
}
// 创建文件服务
func (fileService *FileService) CreateFile(createFileCommand *command.CreateFileCommand) (interface{}, error) {
if err := createFileCommand.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
transactionContext.RollbackTransaction()
}()
newFile := &domain.File{
//Name: createFileCommand.Name,
//Url: createFileCommand.Url,
//FileSize: createFileCommand.FileSize,
}
var fileRepository domain.FileRepository
if value, err := factory.CreateFileRepository(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
fileRepository = value
}
if file, err := fileRepository.Save(newFile); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return file, nil
}
}
// 编辑表格数据
func (fileService *FileService) EditDataTable(editDataTableCommand *command.EditDataTableCommand) (interface{}, error) {
if err := editDataTableCommand.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
transactionContext.RollbackTransaction()
}()
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return nil, nil
}
// 持久化表格数据
func (fileService *FileService) FlushDataTable(flushDataTableCommand *command.FlushDataTableCommand) (interface{}, error) {
if err := flushDataTableCommand.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
transactionContext.RollbackTransaction()
}()
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return nil, nil
}
// 生成主表
func (fileService *FileService) GenerateMainTable(generateMainTableCommand *command.GenerateMainTableCommand) (interface{}, error) {
if err := generateMainTableCommand.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
transactionContext.RollbackTransaction()
}()
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return nil, nil
}
// 返回文件服务
func (fileService *FileService) GetFile(getFileQuery *query.GetFileQuery) (interface{}, error) {
if err := getFileQuery.ValidateQuery(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
transactionContext.RollbackTransaction()
}()
var fileRepository domain.FileRepository
if value, err := factory.CreateFileRepository(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
fileRepository = value
}
file, err := fileRepository.FindOne(map[string]interface{}{"fileId": getFileQuery.FileId})
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if file == nil {
return nil, application.ThrowError(application.RES_NO_FIND_ERROR, fmt.Sprintf("%s", string(getFileQuery.FileId)))
} else {
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return file, nil
}
}
// 返回文件服务列表
func (fileService *FileService) ListFile(listFileQuery *query.ListFileQuery) (interface{}, error) {
if err := listFileQuery.ValidateQuery(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
transactionContext.RollbackTransaction()
}()
var fileRepository domain.FileRepository
if value, err := factory.CreateFileRepository(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
fileRepository = value
}
if count, files, err := fileRepository.Find(tool_funs.SimpleStructToMap(listFileQuery)); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return map[string]interface{}{
"count": count,
"files": files,
}, nil
}
}
// 加载表格数据
func (fileService *FileService) LoadDataTable(loadDataTableCommand *command.LoadDataTableCommand) (interface{}, error) {
if err := loadDataTableCommand.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
transactionContext.RollbackTransaction()
}()
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return nil, nil
}
// 移除文件服务
func (fileService *FileService) RemoveFile(removeFileCommand *command.RemoveFileCommand) (interface{}, error) {
if err := removeFileCommand.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
transactionContext.RollbackTransaction()
}()
var fileRepository domain.FileRepository
if value, err := factory.CreateFileRepository(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
fileRepository = value
}
file, err := fileRepository.FindOne(map[string]interface{}{"fileId": removeFileCommand.FileId})
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if file == nil {
return nil, application.ThrowError(application.RES_NO_FIND_ERROR, fmt.Sprintf("%s", string(removeFileCommand.FileId)))
}
if file, err := fileRepository.Remove(file); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return file, nil
}
}
// 更新文件服务
func (fileService *FileService) UpdateFile(updateFileCommand *command.UpdateFileCommand) (interface{}, error) {
if err := updateFileCommand.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
transactionContext.RollbackTransaction()
}()
var fileRepository domain.FileRepository
if value, err := factory.CreateFileRepository(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
fileRepository = value
}
file, err := fileRepository.FindOne(map[string]interface{}{"fileId": updateFileCommand.FileId})
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if file == nil {
return nil, application.ThrowError(application.RES_NO_FIND_ERROR, fmt.Sprintf("%s", string(updateFileCommand.FileId)))
}
if err := file.Update(tool_funs.SimpleStructToMap(updateFileCommand)); err != nil {
return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
}
if file, err := fileRepository.Save(file); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return file, nil
}
}
func NewFileService(options map[string]interface{}) *FileService {
newFileService := &FileService{}
return newFileService
}
... ...
package application
import (
"github.com/beego/beego/v2/core/validation"
"github.com/linmadan/egglib-go/validation/beego"
)
func init() {
validation.MessageTmpls = beego.ValidationMessageTmpls
}
... ...
package constant
import (
"fmt"
)
var SERVICE_NAME = "character-library-metadata-bastion"
var SERVICE_ENV = "dev"
var HTTP_PORT int = 8081
var CACHE_PREFIX = "character-library-metadata-bastion-dev"
var LOG_LEVEL = "debug"
var LOG_FILE = "app.log"
var PPROF_ON = true
//天联共创基础模块
//var ALLIED_CREATION_BASIC_HOST = "http://localhost:8080" //"http://allied-creation-basic-dev.fjmaimaimai.com"
//天联共创用户模块
var ALLIED_CREATION_USER_HOST = "http://localhost:8081" //"http://allied-creation-user-dev.fjmaimaimai.com"
//天联共创业务模块
//var ALLIED_CREATION_COOPERATION_HOST = "http://localhost:8082" // "http://allied-creation-cooperation-dev.fjmaimaimai.com"
var MMM_BYTE_BANK_HOST = "http://220.250.41.79:8301"
//var CUSTOMER_ACCOUNT = []int64{3129687560814592, 3129687690100739, 3492238958608384}
//const CUSTOMER_ACCOUNT_DELIMITER = ","
/***** 1.数据传输 *****/
//const HeaderCompanyId = "companyId"
//const HeaderUserId = "userId"
//const HeaderOrgId = "orgId"
//const HeaderOrgIds = "orgIds"
func init() {
LOG_LEVEL = Configurator.DefaultString("LOG_LEVEL", LOG_LEVEL)
//ALLIED_CREATION_BASIC_HOST = Configurator.DefaultString("ALLIED_CREATION_BASIC_HOST", ALLIED_CREATION_BASIC_HOST)
ALLIED_CREATION_USER_HOST = Configurator.DefaultString("ALLIED_CREATION_USER_HOST", ALLIED_CREATION_USER_HOST)
//ALLIED_CREATION_COOPERATION_HOST = Configurator.DefaultString("ALLIED_CREATION_COOPERATION_HOST", ALLIED_CREATION_COOPERATION_HOST)
MMM_BYTE_BANK_HOST = Configurator.DefaultString("MMM_BYTE_BANK_HOST", MMM_BYTE_BANK_HOST)
SERVICE_ENV = Configurator.DefaultString("SERVICE_ENV", SERVICE_ENV)
HTTP_PORT = Configurator.DefaultInt("HTTP_PORT", HTTP_PORT)
SERVICE_NAME = fmt.Sprintf("%v-%v", SERVICE_NAME, SERVICE_ENV)
PPROF_ON = Configurator.DefaultBool("PPROF_ON", PPROF_ON)
CACHE_PREFIX = SERVICE_NAME
}
... ...
// go:build !local
//go:build !local
// +build !local
package constant
import "gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/infrastructure/utils"
var Configurator utils.Configurator = utils.NewConfig("ini", "config/app.conf")
... ...
// go:build local
//go:build local
// +build local
package constant
import "gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/infrastructure/utils"
var Configurator utils.Configurator = utils.EnvConfigurator{}
... ...
package constant
var (
// kafka 地址
KAFKA_HOST = "192.168.0.250:9092,192.168.0.251:9092,192.168.0.252:9092" //"106.75.231.90:9092"
// kafka topic log stash
TOPIC_LOG_STASH = "go_stash_dev" //"pushMessage"
// kafka topic up_block_chain
TOPIC_UP_BLOCK_CHAIN = "allied_creation_message"
// 是否启用日志收集 (本地不启用)
ENABLE_KAFKA_LOG = false
)
func init() {
KAFKA_HOST = Configurator.DefaultString("KAFKA_HOST", KAFKA_HOST)
ENABLE_KAFKA_LOG = Configurator.DefaultBool("ENABLE_KAFKA_LOG", ENABLE_KAFKA_LOG)
}
... ...
package constant
var POSTGRESQL_DB_NAME = "terms"
var POSTGRESQL_USER = "postgres"
var POSTGRESQL_PASSWORD = "123456"
var POSTGRESQL_HOST = "127.0.0.1"
var POSTGRESQL_PORT = "5432"
var DISABLE_CREATE_TABLE = false
var DISABLE_SQL_GENERATE_PRINT = false
var DISABLE_SQL_GENERATE_COMMENT = true
func init() {
POSTGRESQL_HOST = Configurator.DefaultString("POSTGRESQL_HOST", POSTGRESQL_HOST)
POSTGRESQL_PORT = Configurator.DefaultString("POSTGRESQL_PORT", POSTGRESQL_PORT)
POSTGRESQL_DB_NAME = Configurator.DefaultString("POSTGRESQL_DB_NAME", POSTGRESQL_DB_NAME)
POSTGRESQL_USER = Configurator.DefaultString("POSTGRESQL_USER", POSTGRESQL_USER)
POSTGRESQL_PASSWORD = Configurator.DefaultString("POSTGRESQL_PASSWORD", POSTGRESQL_PASSWORD)
DISABLE_CREATE_TABLE = Configurator.DefaultBool("DISABLE_CREATE_TABLE", DISABLE_CREATE_TABLE)
DISABLE_SQL_GENERATE_PRINT = Configurator.DefaultBool("DISABLE_SQL_GENERATE_PRINT", DISABLE_SQL_GENERATE_PRINT)
}
... ...
package constant
var (
REDIS_HOST = "127.0.0.1"
REDIS_PORT = "6379"
REDIS_AUTH = ""
REDIS_ADDRESS = ""
// 是否关闭仓储层缓存
ENABLE_REPOSITORY_CACHE = true
// 缓存过期时间 单位秒
REPOSITORY_CACHE_EXPIRE = 30 * 60
// redis 考勤机打卡消息队列
REDIS_ZKTECO_KEY = "allied-creation-zkteco"
// redis 车间数据消息队列
REDIS_WORKSHOP_KEY = "allied-creation-workshop"
)
func init() {
REDIS_HOST = Configurator.DefaultString("REDIS_HOST", REDIS_HOST)
REDIS_PORT = Configurator.DefaultString("REDIS_PORT", REDIS_PORT)
REDIS_AUTH = Configurator.DefaultString("REDIS_AUTH", REDIS_AUTH)
ENABLE_REPOSITORY_CACHE = Configurator.DefaultBool("ENABLE_REPOSITORY_CACHE", ENABLE_REPOSITORY_CACHE)
REDIS_ADDRESS = REDIS_HOST + ":" + REDIS_PORT
}
... ...
package domain
// Field 字段
type Field struct {
// 字段Id
FieldId int `json:"fieldId"`
// 索引序号
Index int `json:"index"`
// 名称
Name string `json:"name"`
// 对应数据库名称
SQLName string `json:"sqlName"`
// 对应数据库类型
SQLType string `json:"sqlType"`
// 描述
Description string `json:"description"`
// 标识 1:主表字段 2:手动添加
Flag int `json:"flag"`
}
... ...
package domain
import "time"
// File 文件
type File struct {
// 文件ID
FileId int `json:"fileId"`
// 文件类型
FileType string `json:"fileType"`
// 文件信息
FileInfo *FileInfo `json:"fileInfo"`
// 源文件Id(FileType为TemporaryFile或VerifiedFile时有值)
SourceFileId string `json:"sourceFileId"`
// 操作人
Operator string `json:"operator"`
// 创建时间
CreatedAt time.Time `json:"createdAt"`
// 更新时间
UpdatedAt time.Time `json:"updatedAt"`
// 删除时间
DeletedAt time.Time `json:"deletedAt"`
// 版本
Version int `json:"version"`
}
type FileRepository interface {
Save(file *File) (*File, error)
Remove(file *File) (*File, error)
FindOne(queryOptions map[string]interface{}) (*File, error)
Find(queryOptions map[string]interface{}) (int64, []*File, error)
}
func (file *File) Identify() interface{} {
if file.FileId == 0 {
return nil
}
return file.FileId
}
func (file *File) Update(data map[string]interface{}) error {
return nil
}
... ...
package domain
// FileInfo 文件信息
type FileInfo struct {
// 名称
Name string `json:"name"`
// 文件地址
Url string `json:"url"`
// 文件大小
FileSize int `json:"fileSize"`
}
... ...
package domain
import "time"
// Log 日志
type Log struct {
// 日志ID
LogId int `json:"logId"`
// 日志类型 1.校验步骤 2.常规日志
LogType int `json:"logType"`
// 源数据ID
SourceId int `json:"sourceId"`
// 日志内容
Entry *LogEntry `json:"entry"`
// 创建时间
CreatedAt time.Time `json:"createdAt"`
}
type LogRepository interface {
Save(log *Log) (*Log, error)
Remove(log *Log) (*Log, error)
FindOne(queryOptions map[string]interface{}) (*Log, error)
Find(queryOptions map[string]interface{}) (int64, []*Log, error)
}
func (log *Log) Identify() interface{} {
if log.LogId == 0 {
return nil
}
return log.LogId
}
func (log *Log) Update(data map[string]interface{}) error {
return nil
}
... ...
package domain
// LogEntry 日志内容
type LogEntry struct {
// 对象名称 数据表名 / 文件名
ObjectName string `json:"objectName"`
// 对象类型 1.主表 2.分表 3.副表 4.源文件 5.校验文件
ObjectType string `json:"objectType"`
// 操作类型 1.主表生成 2.主表拆分 3.数据导入 4.分表生成 5.表复制 6.编辑记录 7.文件上传 8.文件校验
OperationType string `json:"operationType"`
// 日志内容
Content string `json:"content"`
// 操作人名称
OperatorName string `json:"operatorName"`
}
... ...
package domain
import "time"
// Table 表
type Table struct {
// 表Id
TableId int `json:"tableId"`
// 表类型 MainTable:主表 SideTable:副表 SubTable:分表 ExcelTable:Excel表
TableType string `json:"tableType"`
// 名称
Name string `json:"name"`
// 对应数据库名称
SQLName string `json:"sQLName"`
// 父级ID
ParentId int64 `json:"parentId,string"`
// 数据字段序号
DataFieldIndex int `json:"dataFieldIndex"`
// 主键字段
PK string `json:"pK"`
// 数据列
DataFields string `json:"dataFields"`
// 手动添加的列
ManualFields string `json:"manualFields"`
// 创建时间
CreatedAt time.Time `json:"createdAt"`
// 更新时间
UpdatedAt time.Time `json:"updatedAt"`
// 删除时间
DeletedAt time.Time `json:"deletedAt"`
// 版本
Version int `json:"version"`
}
type TableRepository interface {
Save(table *Table) (*Table, error)
Remove(table *Table) (*Table, error)
FindOne(queryOptions map[string]interface{}) (*Table, error)
Find(queryOptions map[string]interface{}) (int64, []*Table, error)
}
func (table *Table) Identify() interface{} {
if table.TableId == 0 {
return nil
}
return table.TableId
}
func (table *Table) Update(data map[string]interface{}) error {
return nil
}
... ...
package pg
import (
"fmt"
"github.com/go-pg/pg/v10"
"github.com/go-pg/pg/v10/orm"
"gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/constant"
//_ "gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/infrastructure/pg/models"
"github.com/linmadan/egglib-go/persistent/pg/comment"
"github.com/linmadan/egglib-go/persistent/pg/hooks"
)
var DB *pg.DB
func init() {
DB = pg.Connect(&pg.Options{
User: constant.POSTGRESQL_USER,
Password: constant.POSTGRESQL_PASSWORD,
Database: constant.POSTGRESQL_DB_NAME,
Addr: fmt.Sprintf("%s:%s", constant.POSTGRESQL_HOST, constant.POSTGRESQL_PORT),
})
if !constant.DISABLE_SQL_GENERATE_PRINT {
DB.AddQueryHook(hooks.SqlGeneratePrintHook{})
}
if !constant.DISABLE_CREATE_TABLE {
for _, model := range []interface{}{} {
err := DB.Model(model).CreateTable(&orm.CreateTableOptions{
Temp: false,
IfNotExists: true,
FKConstraints: true,
})
if err != nil {
panic(err)
}
comment.AddComments(DB, model)
}
}
}
... ...
package models
import (
"gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/domain"
"time"
)
type File struct {
tableName string `comment:"文件" pg:"metadata.files,alias:file"`
// 文件ID
FileId int `comment:"文件ID" pg:"pk:file_id"`
// 文件类型
FileType string `comment:"文件类型"`
// 文件信息
FileInfo *domain.FileInfo `comment:"文件信息"`
// 源文件Id(FileType为TemporaryFile或VerifiedFile时有值)
SourceFileId string `comment:"源文件Id(FileType为TemporaryFile或VerifiedFile时有值)"`
// 操作人
Operator string `comment:"操作人"`
// 创建时间
CreatedAt time.Time `comment:"创建时间"`
// 更新时间
UpdatedAt time.Time `comment:"更新时间"`
// 删除时间
DeletedAt time.Time `comment:"删除时间"`
// 版本
Version int `comment:"版本"`
}
... ...
package models
import (
"gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/domain"
"time"
)
type Log struct {
tableName string `comment:"日志" pg:"metadata.logs,alias:log"`
// 日志ID
LogId int `comment:"日志ID" pg:"pk:log_id"`
// 日志类型 1.校验步骤 2.常规日志
LogType int `comment:"日志类型 1.校验步骤 2.常规日志"`
// 源数据ID
SourceId int `comment:"源数据ID"`
// 日志内容
Entry *domain.LogEntry `comment:"日志内容"`
// 创建时间
CreatedAt time.Time `comment:"创建时间"`
}
... ...
package models
import "time"
type Table struct {
tableName string `comment:"表" pg:"metadata.tables,alias:table"`
// 表Id
TableId int `comment:"表Id" pg:"pk:table_id"`
// 表类型 MainTable:主表 SideTable:副表 SubTable:分表 ExcelTable:Excel表
TableType string `comment:"表类型 MainTable:主表 SideTable:副表 SubTable:分表 ExcelTable:Excel表"`
// 名称
Name string `comment:"名称"`
// 对应数据库名称
SQLName string `comment:"对应数据库名称"`
// 父级ID
ParentId int64 `comment:"父级ID"`
// 数据字段序号
DataFieldIndex int `comment:"数据字段序号"`
// 主键字段
PK string `comment:"主键字段"`
// 数据列
DataFields string `comment:"数据列"`
// 手动添加的列
ManualFields string `comment:"手动添加的列"`
// 创建时间
CreatedAt time.Time `comment:"创建时间"`
// 更新时间
UpdatedAt time.Time `comment:"更新时间"`
// 删除时间
DeletedAt time.Time `comment:"删除时间"`
// 版本
Version int `comment:"版本"`
}
... ...
package transform
import (
"gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/infrastructure/pg/models"
)
func TransformToFileDomainModelFromPgModels(fileModel *models.File) (*domain.File, error) {
return &domain.File{
FileId: fileModel.FileId,
FileType: fileModel.FileType,
FileInfo: fileModel.FileInfo,
SourceFileId: fileModel.SourceFileId,
Operator: fileModel.Operator,
CreatedAt: fileModel.CreatedAt,
UpdatedAt: fileModel.UpdatedAt,
DeletedAt: fileModel.DeletedAt,
Version: fileModel.Version,
}, nil
}
... ...
package transform
import (
"gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/infrastructure/pg/models"
)
func TransformToLogDomainModelFromPgModels(logModel *models.Log) (*domain.Log, error) {
return &domain.Log{
LogId: logModel.LogId,
LogType: logModel.LogType,
SourceId: logModel.SourceId,
Entry: logModel.Entry,
CreatedAt: logModel.CreatedAt,
}, nil
}
... ...
package transform
import (
"gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/infrastructure/pg/models"
)
func TransformToTableDomainModelFromPgModels(tableModel *models.Table) (*domain.Table, error) {
return &domain.Table{
TableId: tableModel.TableId,
TableType: tableModel.TableType,
Name: tableModel.Name,
SQLName: tableModel.SQLName,
ParentId: tableModel.ParentId,
DataFieldIndex: tableModel.DataFieldIndex,
PK: tableModel.PK,
DataFields: tableModel.DataFields,
ManualFields: tableModel.ManualFields,
CreatedAt: tableModel.CreatedAt,
UpdatedAt: tableModel.UpdatedAt,
DeletedAt: tableModel.DeletedAt,
Version: tableModel.Version,
}, nil
}
... ...
package redis
import (
"fmt"
"github.com/go-redis/redis"
"gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/constant"
)
var clientRedis *redis.Client
func InitRedis() *redis.Client {
options := redis.Options{
Network: "tcp",
Addr: fmt.Sprintf("%s:%s", constant.REDIS_HOST, constant.REDIS_PORT),
Dialer: nil,
OnConnect: nil,
Password: "",
DB: 0,
MaxRetries: 0,
MinRetryBackoff: 0,
MaxRetryBackoff: 0,
DialTimeout: 0,
ReadTimeout: 0,
WriteTimeout: 0,
PoolSize: 0,
MinIdleConns: 0,
MaxConnAge: 0,
PoolTimeout: 0,
IdleTimeout: 0,
IdleCheckFrequency: 0,
TLSConfig: nil,
}
// 新建一个client
clientRedis = redis.NewClient(&options)
pong, err := clientRedis.Ping().Result()
if err != nil {
e := fmt.Errorf("redis 连接失败,%s,%w", pong, err)
panic(e)
}
return clientRedis
}
func GetRedis() *redis.Client {
return clientRedis
}
... ...
package repository
import (
"fmt"
"github.com/go-pg/pg/v10"
"github.com/linmadan/egglib-go/persistent/pg/sqlbuilder"
pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
"github.com/linmadan/egglib-go/utils/snowflake"
"gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/infrastructure/pg/models"
"gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/infrastructure/pg/transform"
)
type FileRepository struct {
transactionContext *pgTransaction.TransactionContext
}
func (repository *FileRepository) nextIdentify() (int64, error) {
IdWorker, err := snowflake.NewIdWorker(1)
if err != nil {
return 0, err
}
id, err := IdWorker.NextId()
return id, err
}
func (repository *FileRepository) Save(file *domain.File) (*domain.File, error) {
sqlBuildFields := []string{
"file_id",
"file_type",
"file_info",
"source_file_id",
"operator",
"created_at",
"updated_at",
"deleted_at",
"version",
}
insertFieldsSnippet := sqlbuilder.SqlFieldsSnippet(sqlbuilder.RemoveSqlFields(sqlBuildFields, "file_id", "deleted_at"))
insertPlaceHoldersSnippet := sqlbuilder.SqlPlaceHoldersSnippet(sqlbuilder.RemoveSqlFields(sqlBuildFields, "file_id", "deleted_at"))
returningFieldsSnippet := sqlbuilder.SqlFieldsSnippet(sqlBuildFields)
updateFields := sqlbuilder.RemoveSqlFields(sqlBuildFields, "file_id", "deleted_at")
updateFieldsSnippet := sqlbuilder.SqlUpdateFieldsSnippet(updateFields)
tx := repository.transactionContext.PgTx
if file.Identify() == nil {
if _, err := tx.QueryOne(
pg.Scan(
&file.FileId,
&file.FileType,
&file.FileInfo,
&file.SourceFileId,
&file.Operator,
&file.CreatedAt,
&file.UpdatedAt,
&file.DeletedAt,
&file.Version,
),
fmt.Sprintf("INSERT INTO metadata.files (%s) VALUES (%s) RETURNING %s", insertFieldsSnippet, insertPlaceHoldersSnippet, returningFieldsSnippet),
file.FileId,
file.FileType,
file.FileInfo,
file.SourceFileId,
file.Operator,
file.CreatedAt,
file.UpdatedAt,
file.Version,
); err != nil {
return file, err
}
} else {
if _, err := tx.QueryOne(
pg.Scan(
&file.FileId,
&file.FileType,
&file.FileInfo,
&file.SourceFileId,
&file.Operator,
&file.CreatedAt,
&file.UpdatedAt,
&file.DeletedAt,
&file.Version,
),
fmt.Sprintf("UPDATE metadata.files SET %s WHERE file_id=? RETURNING %s", updateFieldsSnippet, returningFieldsSnippet),
file.FileId,
file.FileType,
file.FileInfo,
file.SourceFileId,
file.Operator,
file.CreatedAt,
file.UpdatedAt,
file.DeletedAt,
file.Version,
file.Identify(),
); err != nil {
return file, err
}
}
return file, nil
}
func (repository *FileRepository) Remove(file *domain.File) (*domain.File, error) {
tx := repository.transactionContext.PgTx
fileModel := new(models.File)
fileModel.FileId = file.Identify().(int)
if _, err := tx.Model(fileModel).WherePK().Delete(); err != nil {
return file, err
}
return file, nil
}
func (repository *FileRepository) FindOne(queryOptions map[string]interface{}) (*domain.File, error) {
tx := repository.transactionContext.PgTx
fileModel := new(models.File)
query := sqlbuilder.BuildQuery(tx.Model(fileModel), queryOptions)
query.SetWhereByQueryOption("file.file_id = ?", "fileId")
if err := query.First(); err != nil {
if err.Error() == "pg: no rows in result set" {
return nil, fmt.Errorf("没有此资源")
} else {
return nil, err
}
}
if fileModel.FileId == 0 {
return nil, nil
} else {
return transform.TransformToFileDomainModelFromPgModels(fileModel)
}
}
func (repository *FileRepository) Find(queryOptions map[string]interface{}) (int64, []*domain.File, error) {
tx := repository.transactionContext.PgTx
var fileModels []*models.File
files := make([]*domain.File, 0)
query := sqlbuilder.BuildQuery(tx.Model(&fileModels), queryOptions)
query.SetOffsetAndLimit(20)
query.SetOrderDirect("file_id", "DESC")
if count, err := query.SelectAndCount(); err != nil {
return 0, files, err
} else {
for _, fileModel := range fileModels {
if file, err := transform.TransformToFileDomainModelFromPgModels(fileModel); err != nil {
return 0, files, err
} else {
files = append(files, file)
}
}
return int64(count), files, nil
}
}
func NewFileRepository(transactionContext *pgTransaction.TransactionContext) (*FileRepository, error) {
if transactionContext == nil {
return nil, fmt.Errorf("transactionContext参数不能为nil")
} else {
return &FileRepository{
transactionContext: transactionContext,
}, nil
}
}
... ...
package repository
import (
"fmt"
"github.com/go-pg/pg/v10"
"github.com/linmadan/egglib-go/persistent/pg/sqlbuilder"
pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
"github.com/linmadan/egglib-go/utils/snowflake"
"gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/infrastructure/pg/models"
"gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/infrastructure/pg/transform"
)
type LogRepository struct {
transactionContext *pgTransaction.TransactionContext
}
func (repository *LogRepository) nextIdentify() (int64, error) {
IdWorker, err := snowflake.NewIdWorker(1)
if err != nil {
return 0, err
}
id, err := IdWorker.NextId()
return id, err
}
func (repository *LogRepository) Save(log *domain.Log) (*domain.Log, error) {
sqlBuildFields := []string{
"log_id",
"log_type",
"source_id",
"entry",
"created_at",
}
insertFieldsSnippet := sqlbuilder.SqlFieldsSnippet(sqlbuilder.RemoveSqlFields(sqlBuildFields, "log_id"))
insertPlaceHoldersSnippet := sqlbuilder.SqlPlaceHoldersSnippet(sqlbuilder.RemoveSqlFields(sqlBuildFields, "log_id"))
returningFieldsSnippet := sqlbuilder.SqlFieldsSnippet(sqlBuildFields)
updateFields := sqlbuilder.RemoveSqlFields(sqlBuildFields, "log_id")
updateFieldsSnippet := sqlbuilder.SqlUpdateFieldsSnippet(updateFields)
tx := repository.transactionContext.PgTx
if log.Identify() == nil {
if _, err := tx.QueryOne(
pg.Scan(
&log.LogId,
&log.LogType,
&log.SourceId,
&log.Entry,
&log.CreatedAt,
),
fmt.Sprintf("INSERT INTO metadata.logs (%s) VALUES (%s) RETURNING %s", insertFieldsSnippet, insertPlaceHoldersSnippet, returningFieldsSnippet),
//log.LogId,
log.LogType,
log.SourceId,
log.Entry,
log.CreatedAt,
); err != nil {
return log, err
}
} else {
if _, err := tx.QueryOne(
pg.Scan(
&log.LogId,
&log.LogType,
&log.SourceId,
&log.Entry,
&log.CreatedAt,
),
fmt.Sprintf("UPDATE metadata.logs SET %s WHERE log_id=? RETURNING %s", updateFieldsSnippet, returningFieldsSnippet),
//log.LogId,
log.LogType,
log.SourceId,
log.Entry,
log.CreatedAt,
log.Identify(),
); err != nil {
return log, err
}
}
return log, nil
}
func (repository *LogRepository) Remove(log *domain.Log) (*domain.Log, error) {
tx := repository.transactionContext.PgTx
logModel := new(models.Log)
logModel.LogId = log.Identify().(int)
if _, err := tx.Model(logModel).WherePK().Delete(); err != nil {
return log, err
}
return log, nil
}
func (repository *LogRepository) FindOne(queryOptions map[string]interface{}) (*domain.Log, error) {
tx := repository.transactionContext.PgTx
logModel := new(models.Log)
query := sqlbuilder.BuildQuery(tx.Model(logModel), queryOptions)
query.SetWhereByQueryOption("log.log_id = ?", "logId")
if err := query.First(); err != nil {
if err.Error() == "pg: no rows in result set" {
return nil, fmt.Errorf("没有此资源")
} else {
return nil, err
}
}
if logModel.LogId == 0 {
return nil, nil
} else {
return transform.TransformToLogDomainModelFromPgModels(logModel)
}
}
func (repository *LogRepository) Find(queryOptions map[string]interface{}) (int64, []*domain.Log, error) {
tx := repository.transactionContext.PgTx
var logModels []*models.Log
logs := make([]*domain.Log, 0)
query := sqlbuilder.BuildQuery(tx.Model(&logModels), queryOptions)
query.SetOffsetAndLimit(20)
query.SetOrderDirect("log_id", "DESC")
if count, err := query.SelectAndCount(); err != nil {
return 0, logs, err
} else {
for _, logModel := range logModels {
if log, err := transform.TransformToLogDomainModelFromPgModels(logModel); err != nil {
return 0, logs, err
} else {
logs = append(logs, log)
}
}
return int64(count), logs, nil
}
}
func NewLogRepository(transactionContext *pgTransaction.TransactionContext) (*LogRepository, error) {
if transactionContext == nil {
return nil, fmt.Errorf("transactionContext参数不能为nil")
} else {
return &LogRepository{
transactionContext: transactionContext,
}, nil
}
}
... ...
package repository
import (
"fmt"
"github.com/go-pg/pg/v10"
"github.com/linmadan/egglib-go/persistent/pg/sqlbuilder"
pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
"github.com/linmadan/egglib-go/utils/snowflake"
"gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/infrastructure/pg/models"
"gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/infrastructure/pg/transform"
)
type TableRepository struct {
transactionContext *pgTransaction.TransactionContext
}
func (repository *TableRepository) nextIdentify() (int64, error) {
IdWorker, err := snowflake.NewIdWorker(1)
if err != nil {
return 0, err
}
id, err := IdWorker.NextId()
return id, err
}
func (repository *TableRepository) Save(table *domain.Table) (*domain.Table, error) {
sqlBuildFields := []string{
"table_id",
"table_type",
"name",
"sql_name",
"parent_id",
"data_field_index",
"pk",
"data_fields",
"manual_fields",
"created_at",
"updated_at",
"deleted_at",
"version",
}
insertFieldsSnippet := sqlbuilder.SqlFieldsSnippet(sqlBuildFields)
insertPlaceHoldersSnippet := sqlbuilder.SqlPlaceHoldersSnippet(sqlBuildFields)
returningFieldsSnippet := sqlbuilder.SqlFieldsSnippet(sqlBuildFields)
updateFields := sqlbuilder.RemoveSqlFields(sqlBuildFields, "table_id")
updateFieldsSnippet := sqlbuilder.SqlUpdateFieldsSnippet(updateFields)
tx := repository.transactionContext.PgTx
if table.Identify() == nil {
if _, err := tx.QueryOne(
pg.Scan(
&table.TableId,
&table.TableType,
&table.Name,
&table.SQLName,
&table.ParentId,
&table.DataFieldIndex,
&table.PK,
&table.DataFields,
&table.ManualFields,
&table.CreatedAt,
&table.UpdatedAt,
&table.DeletedAt,
&table.Version,
),
fmt.Sprintf("INSERT INTO metadata.tables (%s) VALUES (%s) RETURNING %s", insertFieldsSnippet, insertPlaceHoldersSnippet, returningFieldsSnippet),
table.TableId,
table.TableType,
table.Name,
table.SQLName,
table.ParentId,
table.DataFieldIndex,
table.PK,
table.DataFields,
table.ManualFields,
table.CreatedAt,
table.UpdatedAt,
table.DeletedAt,
table.Version,
); err != nil {
return table, err
}
} else {
if _, err := tx.QueryOne(
pg.Scan(
&table.TableId,
&table.TableType,
&table.Name,
&table.SQLName,
&table.ParentId,
&table.DataFieldIndex,
&table.PK,
&table.DataFields,
&table.ManualFields,
&table.CreatedAt,
&table.UpdatedAt,
&table.DeletedAt,
&table.Version,
),
fmt.Sprintf("UPDATE metadata.tables SET %s WHERE table_id=? RETURNING %s", updateFieldsSnippet, returningFieldsSnippet),
table.TableId,
table.TableType,
table.Name,
table.SQLName,
table.ParentId,
table.DataFieldIndex,
table.PK,
table.DataFields,
table.ManualFields,
table.CreatedAt,
table.UpdatedAt,
table.DeletedAt,
table.Version,
table.Identify(),
); err != nil {
return table, err
}
}
return table, nil
}
func (repository *TableRepository) Remove(table *domain.Table) (*domain.Table, error) {
tx := repository.transactionContext.PgTx
tableModel := new(models.Table)
tableModel.TableId = table.Identify().(int)
if _, err := tx.Model(tableModel).WherePK().Delete(); err != nil {
return table, err
}
return table, nil
}
func (repository *TableRepository) FindOne(queryOptions map[string]interface{}) (*domain.Table, error) {
tx := repository.transactionContext.PgTx
tableModel := new(models.Table)
query := sqlbuilder.BuildQuery(tx.Model(tableModel), queryOptions)
query.SetWhereByQueryOption("table.table_id = ?", "tableId")
if err := query.First(); err != nil {
if err.Error() == "pg: no rows in result set" {
return nil, fmt.Errorf("没有此资源")
} else {
return nil, err
}
}
if tableModel.TableId == 0 {
return nil, nil
} else {
return transform.TransformToTableDomainModelFromPgModels(tableModel)
}
}
func (repository *TableRepository) Find(queryOptions map[string]interface{}) (int64, []*domain.Table, error) {
tx := repository.transactionContext.PgTx
var tableModels []*models.Table
tables := make([]*domain.Table, 0)
query := sqlbuilder.BuildQuery(tx.Model(&tableModels), queryOptions)
query.SetOffsetAndLimit(20)
query.SetOrderDirect("table_id", "DESC")
if count, err := query.SelectAndCount(); err != nil {
return 0, tables, err
} else {
for _, tableModel := range tableModels {
if table, err := transform.TransformToTableDomainModelFromPgModels(tableModel); err != nil {
return 0, tables, err
} else {
tables = append(tables, table)
}
}
return int64(count), tables, nil
}
}
func NewTableRepository(transactionContext *pgTransaction.TransactionContext) (*TableRepository, error) {
if transactionContext == nil {
return nil, fmt.Errorf("transactionContext参数不能为nil")
} else {
return &TableRepository{
transactionContext: transactionContext,
}, nil
}
}
... ...
package utils
import (
"github.com/beego/beego/v2/core/config"
"github.com/beego/beego/v2/server/web"
"os"
"strconv"
)
type Configurator interface {
DefaultString(key string, defaultVal string) string
DefaultInt(key string, defaultVal int) int
DefaultInt64(key string, defaultVal int64) int64
DefaultBool(key string, defaultVal bool) bool
DefaultFloat(key string, defaultVal float64) float64
}
// EnvConfigurator read config from env param with default value
type EnvConfigurator struct{}
func (c EnvConfigurator) DefaultString(key string, defaultVal string) string {
if os.Getenv(key) != "" {
return os.Getenv(key)
}
return defaultVal
}
func (c EnvConfigurator) DefaultInt(key string, defaultVal int) int {
if os.Getenv(key) == "" {
return defaultVal
}
v, err := strconv.Atoi(os.Getenv(key))
if err != nil {
return defaultVal
}
return v
}
func (c EnvConfigurator) DefaultInt64(key string, defaultVal int64) int64 {
if os.Getenv(key) == "" {
return defaultVal
}
v, err := strconv.ParseInt(os.Getenv(key), 10, 64)
if err != nil {
return defaultVal
}
return v
}
func (c EnvConfigurator) DefaultBool(key string, defaultVal bool) bool {
if os.Getenv(key) == "" {
return defaultVal
}
v, err := strconv.ParseBool(os.Getenv(key))
if err != nil {
return defaultVal
}
return v
}
func (c EnvConfigurator) DefaultFloat(key string, defaultVal float64) float64 {
if os.Getenv(key) == "" {
return defaultVal
}
v, err := strconv.ParseFloat(os.Getenv(key), 64)
if err != nil {
return defaultVal
}
return v
}
// BeegoAppConfigurator read config from beego config file with default value
type BeegoAppConfigurator struct {
}
func (c BeegoAppConfigurator) DefaultString(key string, defaultVal string) string {
return web.AppConfig.DefaultString(key, defaultVal)
}
func (c BeegoAppConfigurator) DefaultInt(key string, defaultVal int) int {
return web.AppConfig.DefaultInt(key, defaultVal)
}
func (c BeegoAppConfigurator) DefaultInt64(key string, defaultVal int64) int64 {
return web.AppConfig.DefaultInt64(key, defaultVal)
}
func (c BeegoAppConfigurator) DefaultBool(key string, defaultVal bool) bool {
return web.AppConfig.DefaultBool(key, defaultVal)
}
func (c BeegoAppConfigurator) DefaultFloat(key string, defaultVal float64) float64 {
return web.AppConfig.DefaultFloat(key, defaultVal)
}
func NewConfig(adapterName, filename string) Configurator {
config, err := config.NewConfig(adapterName, filename)
if err != nil {
panic(err)
}
return config
}
... ...
package utils
import (
"github.com/stretchr/testify/assert"
"os"
"testing"
)
func TestEnvConfigurator(t *testing.T) {
os.Setenv("bool", "true")
os.Setenv("hello", "world")
os.Setenv("number", "10")
var config Configurator = EnvConfigurator{}
assert.Equal(t, "world", config.DefaultString("hello", "w"))
assert.Equal(t, "w", config.DefaultString("unknown", "w"))
assert.Equal(t, true, config.DefaultBool("bool", false))
assert.Equal(t, true, config.DefaultBool("unknown", true))
assert.Equal(t, 10, config.DefaultInt("number", 5))
assert.Equal(t, 5, config.DefaultInt("unknown", 5))
assert.Equal(t, int64(10), config.DefaultInt64("number", 5))
assert.Equal(t, int64(5), config.DefaultInt64("unknown", 5))
assert.Equal(t, float64(10), config.DefaultFloat("number", 5))
assert.Equal(t, float64(5), config.DefaultFloat("unknown", 5))
}
... ...
package log
import (
"github.com/linmadan/egglib-go/log"
"github.com/linmadan/egglib-go/log/logrus"
"gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/constant"
"io"
)
var Logger log.Logger
func init() {
Logger = logrus.NewLogrusLogger()
Logger.SetServiceName(constant.SERVICE_NAME)
Logger.SetLevel(constant.LOG_LEVEL)
}
func InitLogHook(enableKafka bool, enableBeeLog bool) {
if enableKafka {
if w, err := logrus.NewKafkaWriter(constant.KAFKA_HOST, constant.TOPIC_LOG_STASH, false); err == nil {
Logger.AddHook(w)
} else {
Logger.Error(err.Error())
}
}
if enableBeeLog {
if w, err := logrus.NewWrapHook(true, func() (io.Writer, error) {
return logrus.NewBeegoLogWriter("", `{"filename":"app.log","maxsize":2048000}`)
}); err == nil {
Logger.AddHook(w)
} else {
Logger.Error(err.Error())
}
}
}
//var Logger *LogrusLogger
//
//func init() {
// Logger = NewLogrusLogger()
// Logger.SetServiceName(constant.SERVICE_NAME)
// Logger.SetLevel(constant.LOG_LEVEL)
//}
... ...
package log
//func init() {
// logrus.SetFormatter(&logrus.JSONFormatter{})
// logrus.SetOutput(os.Stdout)
// logrus.SetLevel(logrus.WarnLevel)
//}
//
//type LogrusLogger struct {
// serviceName string
// logrus *logrus.Logger
//}
//
//func (logger *LogrusLogger) SetServiceName(serviceName string) {
// logger.serviceName = serviceName
//}
//
//func (logger *LogrusLogger) SetLevel(level string) {
// switch level {
// case "trace":
// logger.logrus.Level = logrus.TraceLevel
// case "debug":
// logger.logrus.Level = logrus.DebugLevel
// case "info":
// logger.logrus.Level = logrus.InfoLevel
// case "warn":
// logger.logrus.Level = logrus.WarnLevel
// case "error":
// logger.logrus.Level = logrus.ErrorLevel
// case "fatal":
// logger.logrus.Level = logrus.FatalLevel
// case "panic":
// logger.logrus.Level = logrus.PanicLevel
// default:
// logger.logrus.Level = logrus.DebugLevel
// }
//}
//
//func (logger *LogrusLogger) AddHook(w io.Writer) {
// level := logger.logrus.Level
// var levels []logrus.Level
// // 默认已经添加了一个当前log level的hook,所以此处 level+1
// for i := 0; i <= (int(level)); i++ {
// levels = append(levels, logrus.Level(i))
// }
// logger.logrus.AddHook(&writer.Hook{
// Writer: w,
// LogLevels: levels,
// })
//}
//
//func (logger *LogrusLogger) Trace(msg string, appends ...map[string]interface{}) {
// contextLogger := logger.logrus.WithFields(logrus.Fields{"serviceName": logger.serviceName})
// for _, append := range appends {
// contextLogger = contextLogger.WithFields(append)
// }
// contextLogger.Trace(msg)
//}
//
//func (logger *LogrusLogger) Debug(msg string, appends ...map[string]interface{}) {
// contextLogger := logger.logrus.WithFields(logrus.Fields{"serviceName": logger.serviceName})
// for _, append := range appends {
// contextLogger = contextLogger.WithFields(append)
// }
// contextLogger.Debug(msg)
//}
//
//func (logger *LogrusLogger) Info(msg string, appends ...map[string]interface{}) {
// contextLogger := logger.logrus.WithFields(logrus.Fields{"serviceName": logger.serviceName})
// for _, append := range appends {
// contextLogger = contextLogger.WithFields(append)
// }
// contextLogger.Info(msg)
//}
//
//func (logger *LogrusLogger) Warn(msg string, appends ...map[string]interface{}) {
// contextLogger := logger.logrus.WithFields(logrus.Fields{"serviceName": logger.serviceName})
// for _, append := range appends {
// contextLogger = contextLogger.WithFields(append)
// }
// contextLogger.Warn(msg)
//}
//
//func (logger *LogrusLogger) Error(msg string, appends ...map[string]interface{}) {
// contextLogger := logger.logrus.WithFields(logrus.Fields{"serviceName": logger.serviceName})
// for _, append := range appends {
// contextLogger = contextLogger.WithFields(append)
// }
// contextLogger.Error(msg)
//}
//
//func (logger *LogrusLogger) Fatal(msg string, appends ...map[string]interface{}) {
// contextLogger := logger.logrus.WithFields(logrus.Fields{"serviceName": logger.serviceName})
// for _, append := range appends {
// contextLogger = contextLogger.WithFields(append)
// }
// contextLogger.Fatal(msg)
//}
//
//func (logger *LogrusLogger) Panic(msg string, appends ...map[string]interface{}) {
// contextLogger := logger.logrus.WithFields(logrus.Fields{"serviceName": logger.serviceName})
// for _, append := range appends {
// contextLogger = contextLogger.WithFields(append)
// }
// contextLogger.Panic(msg)
//}
//
//func NewLogrusLogger() *LogrusLogger {
// logger := logrus.New()
// logger.Formatter = &logrus.JSONFormatter{}
// logger.Out = os.Stdout
// return &LogrusLogger{
// logrus: logger,
// }
//}
//
//var _ log.Logger = (*LogrusLogger)(nil)
... ...
package log
//import (
// "encoding/json"
// "errors"
// "fmt"
// "github.com/beego/beego/v2/core/logs"
// "io"
// "sync/atomic"
//)
//
//var errOutOfMaxSize = errors.New("msg size is out of limit ")
//
//type BaseHook struct {
// syncWrite bool
// msgChan chan []byte
// maxSize int32
// currentSize int32
// closeChan chan struct{}
// w io.Writer
//}
//
//func (b *BaseHook) Write(p []byte) (n int, err error) {
// if b.syncWrite {
// return b.w.Write(p)
// }
// if b.currentSize >= b.maxSize {
// fmt.Println(errOutOfMaxSize.Error(), b.currentSize)
// return 0, errOutOfMaxSize
// }
// b.msgChan <- p
// atomic.AddInt32(&b.currentSize, 1)
//
// return len(p), nil
//}
//
//// NewBaseHook
//// syncWriteFlag 同步写标识 true:同步写 false:异步写
//func NewBaseHook(syncWriteFlag bool, internalIo io.WriteCloser) (*BaseHook, error) {
// writer := &BaseHook{
// syncWrite: syncWriteFlag,
// maxSize: 10000,
// msgChan: make(chan []byte, 10000),
// closeChan: make(chan struct{}),
// w: internalIo,
// }
// go writer.ConsumeMsg()
// return writer, nil
//}
//
//func (b *BaseHook) ConsumeMsg() {
// for {
// select {
// case <-b.closeChan:
// return
// case m, ok := <-b.msgChan:
// if ok {
// atomic.AddInt32(&b.currentSize, -1)
// if _, err := b.w.Write(m); err != nil {
// fmt.Println(err)
// }
// }
// }
// }
//}
//
//func (b *BaseHook) Close() {
// close(b.msgChan)
// b.closeChan <- struct{}{}
// //b.wc.Close()
//}
//
//type LoggerConfig struct {
// Level int `json:"level,omitempty"`
// Filename string `json:"filename,omitempty"`
// MaxSize int `json:"maxsize,omitempty"`
// //MaxBackups int `json:"max_backups,omitempty"`
// //MaxAge int `json:"max_age,omitempty"`
// //Compress bool `json:"compress,omitempty"`
// //文件最多保存多少天,默认保存 7 天
// //MaxDays int `json:"maxdays"`
//}
//
//type internalLog struct {
// *logs.BeeLogger
//}
//
//func NewBeegoLogWriter(conf LoggerConfig) io.Writer {
// logger := logs.GetBeeLogger()
// logger.SetLevel(conf.Level)
// logger.EnableFuncCallDepth(true)
// logger.SetLogFuncCallDepth(2)
// confByte, _ := json.Marshal(conf)
// err := logger.SetLogger(logs.AdapterFile, string(confByte))
// if err != nil {
// fmt.Println(err.Error())
// }
// return &internalLog{logger}
//}
//
//func (l *internalLog) Write(p []byte) (n int, err error) {
// l.Debug(string(p))
// return len(p), nil
//}
... ...
package beego
import (
"github.com/beego/beego/v2/server/web"
"github.com/linmadan/egglib-go/web/beego/filters"
"os"
"strconv"
. "gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/log"
_ "gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/port/beego/routers"
)
func init() {
web.BConfig.AppName = "character-library-metadata-bastion"
web.BConfig.CopyRequestBody = true
web.BConfig.RunMode = "dev"
web.BConfig.Listen.HTTPPort = 8080
web.BConfig.Listen.EnableAdmin = false
web.BConfig.WebConfig.CommentRouterPath = "/pkg/port/beego/routers"
if os.Getenv("RUN_MODE") != "" {
web.BConfig.RunMode = os.Getenv("RUN_MODE")
}
if os.Getenv("HTTP_PORT") != "" {
portStr := os.Getenv("HTTP_PORT")
if port, err := strconv.Atoi(portStr); err == nil {
web.BConfig.Listen.HTTPPort = port
}
}
web.InsertFilter("/*", web.BeforeExec, filters.AllowCors())
web.InsertFilter("/*", web.BeforeExec, filters.CreateRequstLogFilter(Logger))
web.InsertFilter("/*", web.AfterExec, filters.CreateResponseLogFilter(Logger), web.WithReturnOnOutput(false))
}
... ...
package controllers
import (
"github.com/linmadan/egglib-go/web/beego"
"gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/application/file/command"
"gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/application/file/query"
"gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/application/file/service"
)
type FileController struct {
beego.BaseController
}
func (controller *FileController) CreateFile() {
fileService := service.NewFileService(nil)
createFileCommand := &command.CreateFileCommand{}
controller.Unmarshal(createFileCommand)
data, err := fileService.CreateFile(createFileCommand)
controller.Response(data, err)
}
func (controller *FileController) UpdateFile() {
fileService := service.NewFileService(nil)
updateFileCommand := &command.UpdateFileCommand{}
controller.Unmarshal(updateFileCommand)
fileId, _ := controller.GetInt(":fileId")
updateFileCommand.FileId = fileId
data, err := fileService.UpdateFile(updateFileCommand)
controller.Response(data, err)
}
func (controller *FileController) GetFile() {
fileService := service.NewFileService(nil)
getFileQuery := &query.GetFileQuery{}
fileId, _ := controller.GetInt(":fileId")
getFileQuery.FileId = fileId
data, err := fileService.GetFile(getFileQuery)
controller.Response(data, err)
}
func (controller *FileController) RemoveFile() {
fileService := service.NewFileService(nil)
removeFileCommand := &command.RemoveFileCommand{}
controller.Unmarshal(removeFileCommand)
fileId, _ := controller.GetInt(":fileId")
removeFileCommand.FileId = fileId
data, err := fileService.RemoveFile(removeFileCommand)
controller.Response(data, err)
}
func (controller *FileController) ListFile() {
fileService := service.NewFileService(nil)
listFileQuery := &query.ListFileQuery{}
offset, _ := controller.GetInt("offset")
listFileQuery.Offset = offset
limit, _ := controller.GetInt("limit")
listFileQuery.Limit = limit
data, err := fileService.ListFile(listFileQuery)
controller.Response(data, err)
}
func (controller *FileController) LoadDataTable() {
fileService := service.NewFileService(nil)
loadDataTableCommand := &command.LoadDataTableCommand{}
controller.Unmarshal(loadDataTableCommand)
data, err := fileService.LoadDataTable(loadDataTableCommand)
controller.Response(data, err)
}
func (controller *FileController) EditDataTable() {
fileService := service.NewFileService(nil)
editDataTableCommand := &command.EditDataTableCommand{}
controller.Unmarshal(editDataTableCommand)
data, err := fileService.EditDataTable(editDataTableCommand)
controller.Response(data, err)
}
func (controller *FileController) FlushDataTable() {
fileService := service.NewFileService(nil)
flushDataTableCommand := &command.FlushDataTableCommand{}
controller.Unmarshal(flushDataTableCommand)
data, err := fileService.FlushDataTable(flushDataTableCommand)
controller.Response(data, err)
}
func (controller *FileController) GenerateMainTable() {
fileService := service.NewFileService(nil)
generateMainTableCommand := &command.GenerateMainTableCommand{}
controller.Unmarshal(generateMainTableCommand)
data, err := fileService.GenerateMainTable(generateMainTableCommand)
controller.Response(data, err)
}
... ...
package routers
import (
"github.com/beego/beego/v2/server/web"
"gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/port/beego/controllers"
)
func init() {
web.Router("/bastion/files/", &controllers.FileController{}, "Post:CreateFile")
web.Router("/bastion/files/:fileId", &controllers.FileController{}, "Put:UpdateFile")
web.Router("/bastion/files/:fileId", &controllers.FileController{}, "Get:GetFile")
web.Router("/bastion/files/:fileId", &controllers.FileController{}, "Delete:RemoveFile")
web.Router("/bastion/files/", &controllers.FileController{}, "Get:ListFile")
web.Router("/bastion/load-data-table", &controllers.FileController{}, "Post:LoadDataTable")
web.Router("/bastion/edit-data-table", &controllers.FileController{}, "Post:EditDataTable")
web.Router("/bastion/flush-data-table", &controllers.FileController{}, "Post:FlushDataTable")
web.Router("/bastion/generate-main-table", &controllers.FileController{}, "Post:GenerateMainTable")
}
... ...
package file
import (
"net/http"
"github.com/gavv/httpexpect"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
pG "gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/infrastructure/pg"
)
var _ = Describe("创建文件服务", func() {
Describe("提交数据创建文件服务", func() {
Context("提交正确的新文件数据", func() {
It("返回文件数据", func() {
httpExpect := httpexpect.New(GinkgoT(), server.URL)
body := map[string]interface{}{
"name": "string",
"url": "string",
"fileSize": "int",
}
httpExpect.POST("/files/").
WithJSON(body).
Expect().
Status(http.StatusOK).
JSON().
Object().
ContainsKey("code").ValueEqual("code", 0).
ContainsKey("msg").ValueEqual("msg", "ok").
ContainsKey("data").Value("data").Object().
ContainsKey("fileId").ValueNotEqual("fileId", BeZero())
})
})
})
AfterEach(func() {
_, err := pG.DB.Exec("DELETE FROM files WHERE true")
Expect(err).NotTo(HaveOccurred())
})
})
... ...
package file
import (
"github.com/go-pg/pg/v10"
"net/http"
"github.com/gavv/httpexpect"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
pG "gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/infrastructure/pg"
)
var _ = Describe("编辑表格数据", func() {
var fileId int64
BeforeEach(func() {
_, err := pG.DB.QueryOne(
pg.Scan(&fileId),
"INSERT INTO files (file_id, file_type, file_info, source_file_id, operator, created_at, updated_at, deleted_at, version) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING file_id",
"testFileId", "testFileType", "testFileInfo", "testSourceFileId", "testOperator", "testCreatedAt", "testUpdatedAt", "testDeletedAt", "testVersion")
Expect(err).NotTo(HaveOccurred())
})
Describe("编辑表格数据", func() {
Context("", func() {
It("", func() {
httpExpect := httpexpect.New(GinkgoT(), server.URL)
body := map[string]interface{}{
"fileId": "int",
}
httpExpect.POST("/files/files/edit-data-table").
WithJSON(body).
Expect().
Status(http.StatusOK).
JSON().
Object().
ContainsKey("code").ValueEqual("code", 0).
ContainsKey("msg").ValueEqual("msg", "ok").
ContainsKey("data").Value("data").Object()
})
})
})
AfterEach(func() {
_, err := pG.DB.Exec("DELETE FROM files WHERE true")
Expect(err).NotTo(HaveOccurred())
})
})
... ...
package file
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/beego/beego/v2/server/web"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
_ "gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/application"
_ "gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/infrastructure/pg"
_ "gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/port/beego"
)
func TestFile(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "Beego Port File Correlations Test Case Suite")
}
var handler http.Handler
var server *httptest.Server
var _ = BeforeSuite(func() {
handler = web.BeeApp.Handlers
server = httptest.NewServer(handler)
})
var _ = AfterSuite(func() {
server.Close()
})
... ...
package file
import (
"github.com/go-pg/pg/v10"
"net/http"
"github.com/gavv/httpexpect"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
pG "gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/infrastructure/pg"
)
var _ = Describe("持久化表格数据", func() {
var fileId int64
BeforeEach(func() {
_, err := pG.DB.QueryOne(
pg.Scan(&fileId),
"INSERT INTO files (file_id, file_type, file_info, source_file_id, operator, created_at, updated_at, deleted_at, version) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING file_id",
"testFileId", "testFileType", "testFileInfo", "testSourceFileId", "testOperator", "testCreatedAt", "testUpdatedAt", "testDeletedAt", "testVersion")
Expect(err).NotTo(HaveOccurred())
})
Describe("持久化表格数据", func() {
Context("", func() {
It("", func() {
httpExpect := httpexpect.New(GinkgoT(), server.URL)
body := map[string]interface{}{
"fileId": "int",
}
httpExpect.POST("/files/files/flush-data-table").
WithJSON(body).
Expect().
Status(http.StatusOK).
JSON().
Object().
ContainsKey("code").ValueEqual("code", 0).
ContainsKey("msg").ValueEqual("msg", "ok").
ContainsKey("data").Value("data").Object()
})
})
})
AfterEach(func() {
_, err := pG.DB.Exec("DELETE FROM files WHERE true")
Expect(err).NotTo(HaveOccurred())
})
})
... ...
package file
import (
"github.com/go-pg/pg/v10"
"net/http"
"github.com/gavv/httpexpect"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
pG "gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/infrastructure/pg"
)
var _ = Describe("生成主表", func() {
var fileId int64
BeforeEach(func() {
_, err := pG.DB.QueryOne(
pg.Scan(&fileId),
"INSERT INTO files (file_id, file_type, file_info, source_file_id, operator, created_at, updated_at, deleted_at, version) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING file_id",
"testFileId", "testFileType", "testFileInfo", "testSourceFileId", "testOperator", "testCreatedAt", "testUpdatedAt", "testDeletedAt", "testVersion")
Expect(err).NotTo(HaveOccurred())
})
Describe("生成主表", func() {
Context("", func() {
It("", func() {
httpExpect := httpexpect.New(GinkgoT(), server.URL)
body := map[string]interface{}{
"fileId": "int",
}
httpExpect.POST("/files/files/generate-main-table").
WithJSON(body).
Expect().
Status(http.StatusOK).
JSON().
Object().
ContainsKey("code").ValueEqual("code", 0).
ContainsKey("msg").ValueEqual("msg", "ok").
ContainsKey("data").Value("data").Object()
})
})
})
AfterEach(func() {
_, err := pG.DB.Exec("DELETE FROM files WHERE true")
Expect(err).NotTo(HaveOccurred())
})
})
... ...
package file
import (
"github.com/go-pg/pg/v10"
"net/http"
"github.com/gavv/httpexpect"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
pG "gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/infrastructure/pg"
)
var _ = Describe("返回文件服务", func() {
var fileId int64
BeforeEach(func() {
_, err := pG.DB.QueryOne(
pg.Scan(&fileId),
"INSERT INTO files (file_id, file_type, file_info, source_file_id, operator, created_at, updated_at, deleted_at, version) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING file_id",
"testFileId", "testFileType", "testFileInfo", "testSourceFileId", "testOperator", "testCreatedAt", "testUpdatedAt", "testDeletedAt", "testVersion")
Expect(err).NotTo(HaveOccurred())
})
Describe("根据fileId参数返回文件", func() {
Context("传入有效的fileId", func() {
It("返回文件数据", func() {
httpExpect := httpexpect.New(GinkgoT(), server.URL)
httpExpect.GET("/files/{fileId}").
Expect().
Status(http.StatusOK).
JSON().
Object().
ContainsKey("code").ValueEqual("code", 0).
ContainsKey("msg").ValueEqual("msg", "ok").
ContainsKey("data").Value("data").Object()
})
})
})
AfterEach(func() {
_, err := pG.DB.Exec("DELETE FROM files WHERE true")
Expect(err).NotTo(HaveOccurred())
})
})
... ...
package file
import (
"github.com/go-pg/pg/v10"
"net/http"
"github.com/gavv/httpexpect"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
pG "gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/infrastructure/pg"
)
var _ = Describe("返回文件服务列表", func() {
var fileId int64
BeforeEach(func() {
_, err := pG.DB.QueryOne(
pg.Scan(&fileId),
"INSERT INTO files (file_id, file_type, file_info, source_file_id, operator, created_at, updated_at, deleted_at, version) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING file_id",
"testFileId", "testFileType", "testFileInfo", "testSourceFileId", "testOperator", "testCreatedAt", "testUpdatedAt", "testDeletedAt", "testVersion")
Expect(err).NotTo(HaveOccurred())
})
Describe("根据参数返回文件列表", func() {
Context("传入有效的参数", func() {
It("返回文件数据列表", func() {
httpExpect := httpexpect.New(GinkgoT(), server.URL)
httpExpect.GET("/files/").
WithQuery("offset", "int").
WithQuery("limit", "int").
Expect().
Status(http.StatusOK).
JSON().
Object().
ContainsKey("code").ValueEqual("code", 0).
ContainsKey("msg").ValueEqual("msg", "ok").
ContainsKey("data").Value("data").Object().
ContainsKey("count").ValueEqual("count", 1).
ContainsKey("files").Value("files").Array()
})
})
})
AfterEach(func() {
_, err := pG.DB.Exec("DELETE FROM files WHERE true")
Expect(err).NotTo(HaveOccurred())
})
})
... ...
package file
import (
"github.com/go-pg/pg/v10"
"net/http"
"github.com/gavv/httpexpect"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
pG "gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/infrastructure/pg"
)
var _ = Describe("加载表格数据", func() {
var fileId int64
BeforeEach(func() {
_, err := pG.DB.QueryOne(
pg.Scan(&fileId),
"INSERT INTO files (file_id, file_type, file_info, source_file_id, operator, created_at, updated_at, deleted_at, version) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING file_id",
"testFileId", "testFileType", "testFileInfo", "testSourceFileId", "testOperator", "testCreatedAt", "testUpdatedAt", "testDeletedAt", "testVersion")
Expect(err).NotTo(HaveOccurred())
})
Describe("加载表格数据", func() {
Context("", func() {
It("", func() {
httpExpect := httpexpect.New(GinkgoT(), server.URL)
body := map[string]interface{}{
"fileId": "int",
}
httpExpect.POST("/files/files/load-data-table").
WithJSON(body).
Expect().
Status(http.StatusOK).
JSON().
Object().
ContainsKey("code").ValueEqual("code", 0).
ContainsKey("msg").ValueEqual("msg", "ok").
ContainsKey("data").Value("data").Object()
})
})
})
AfterEach(func() {
_, err := pG.DB.Exec("DELETE FROM files WHERE true")
Expect(err).NotTo(HaveOccurred())
})
})
... ...
package file
import (
"github.com/go-pg/pg/v10"
"net/http"
"github.com/gavv/httpexpect"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
pG "gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/infrastructure/pg"
)
var _ = Describe("移除文件服务", func() {
var fileId int64
BeforeEach(func() {
_, err := pG.DB.QueryOne(
pg.Scan(&fileId),
"INSERT INTO files (file_id, file_type, file_info, source_file_id, operator, created_at, updated_at, deleted_at, version) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING file_id",
"testFileId", "testFileType", "testFileInfo", "testSourceFileId", "testOperator", "testCreatedAt", "testUpdatedAt", "testDeletedAt", "testVersion")
Expect(err).NotTo(HaveOccurred())
})
Describe("根据参数移除文件服务", func() {
Context("传入有效的fileId", func() {
It("返回被移除文件的数据", func() {
httpExpect := httpexpect.New(GinkgoT(), server.URL)
httpExpect.DELETE("/files/{fileId}").
Expect().
Status(http.StatusOK).
JSON().
Object().
ContainsKey("code").ValueEqual("code", 0).
ContainsKey("msg").ValueEqual("msg", "ok").
ContainsKey("data").Value("data").Object()
})
})
})
AfterEach(func() {
_, err := pG.DB.Exec("DELETE FROM files WHERE true")
Expect(err).NotTo(HaveOccurred())
})
})
... ...
package file
import (
"github.com/go-pg/pg/v10"
"net/http"
"github.com/gavv/httpexpect"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
pG "gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/infrastructure/pg"
)
var _ = Describe("更新文件服务", func() {
var fileId int64
BeforeEach(func() {
_, err := pG.DB.QueryOne(
pg.Scan(&fileId),
"INSERT INTO files (file_id, file_type, file_info, source_file_id, operator, created_at, updated_at, deleted_at, version) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING file_id",
"testFileId", "testFileType", "testFileInfo", "testSourceFileId", "testOperator", "testCreatedAt", "testUpdatedAt", "testDeletedAt", "testVersion")
Expect(err).NotTo(HaveOccurred())
})
Describe("提交数据更新文件服务", func() {
Context("提交正确的文件数据", func() {
It("返回更新后的文件数据", func() {
httpExpect := httpexpect.New(GinkgoT(), server.URL)
body := map[string]interface{}{}
httpExpect.PUT("/files/{fileId}").
WithJSON(body).
Expect().
Status(http.StatusOK).
JSON().
Object().
ContainsKey("code").ValueEqual("code", 0).
ContainsKey("msg").ValueEqual("msg", "ok").
ContainsKey("data").Value("data").Object().
ContainsKey("fileId").ValueEqual("fileId", fileId)
})
})
})
AfterEach(func() {
_, err := pG.DB.Exec("DELETE FROM files WHERE true")
Expect(err).NotTo(HaveOccurred())
})
})
... ...