Skip to content

Commit 1aecefd

Browse files
committed
pretty code
1 parent bb33308 commit 1aecefd

File tree

10 files changed

+64
-76
lines changed

10 files changed

+64
-76
lines changed

src/aliyun/oss.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,7 @@ export class OssUtils {
7171
if (!config.response.ok) {
7272
return config as any;
7373
}
74-
74+
7575
if (aliyunContext.stsToken === undefined || Number(aliyunContext.stsToken.expiration) <= Date.now().valueOf()) {
7676
const r = await this.request<AliyunStsToken>(this.options.stsTokenURL, {
7777
method: "GET",
@@ -83,7 +83,7 @@ export class OssUtils {
8383
return r as any; // 发生错误,类型无所谓
8484
}
8585
}
86-
86+
8787
return { data: aliyunContext, response: { ok: true } } as any;
8888
}
8989

src/aliyun/types.ts

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,5 @@ export interface AliyunOssConfig {
1818
}
1919

2020
export interface AliyunConfig {
21-
oss: AliyunOssConfig
21+
oss: AliyunOssConfig;
2222
}
23-

src/minio/index.ts

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,4 +2,3 @@ import { MinioUtils } from "./minio";
22

33
export * from "./types";
44
export * from "./minio";
5-

src/minio/minio.ts

Lines changed: 30 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import { AssumedCredentials, MinioConfig } from ".";
44
import { ExtendedRequestMethod, ExtendedRequestOptionsInit } from "../request";
55
import { ApplicationError, BucketPolicy } from "../core";
66
import * as Minio from "minio";
7-
import { UploadResult } from "./types";
7+
import { PresignedResult, UploadResult } from "./types";
88

99
export interface MinioOptions {
1010
configURL: string;
@@ -21,13 +21,11 @@ interface MinioContext {
2121
const minioContext: MinioContext = { tokenTime: Date.now().valueOf() };
2222

2323
type SimpleStringValue = {
24-
value: string
25-
}
24+
value: string;
25+
};
2626

2727
export class MinioUtils {
28-
private constructor(private request: ExtendedRequestMethod, public options: MinioOptions) {
29-
30-
}
28+
private constructor(private request: ExtendedRequestMethod, public options: MinioOptions) {}
3129

3230
static create(request: ExtendedRequestMethod, serverBaseUrl: string) {
3331
const url = (serverBaseUrl || "").trim();
@@ -76,14 +74,14 @@ export class MinioUtils {
7674
// 提前三分钟过期
7775
const durationMills = durationSeconds ? (durationSeconds - 180) * 1000 : 0;
7876

79-
if (minioContext.stsToken === undefined || (minioContext.tokenTime + durationMills) <= Date.now().valueOf()) {
77+
if (minioContext.stsToken === undefined || minioContext.tokenTime + durationMills <= Date.now().valueOf()) {
8078
const r = await this.request<AssumedCredentials>(this.options.stsTokenURL, {
8179
method: "POST",
8280
skipNotifyError: true
8381
});
8482
if (r.response.ok) {
8583
minioContext.stsToken = r.data;
86-
minioContext.tokenTime = Date.now().valueOf()
84+
minioContext.tokenTime = Date.now().valueOf();
8785
} else {
8886
return r as any; // 发生错误,类型无所谓
8987
}
@@ -92,11 +90,9 @@ export class MinioUtils {
9290
return { data: minioContext, response: { ok: true } } as any;
9391
}
9492

95-
9693
public generateObjectUrl(key: string): string | undefined {
9794
const config = minioContext.config;
9895
if (config && !isNullOrEmptyString(config.publicBucket)) {
99-
10096
const file = key.startsWith("/") ? key.substr(1, key.length - 1) : key;
10197
if (config.port) {
10298
return `${config.schema}://${config.host}:${config.port}/${config.publicBucket}/${file}`;
@@ -109,73 +105,64 @@ export class MinioUtils {
109105
public async presignedObjectUrl(
110106
filePath: string,
111107
resOptions?: Omit<ExtendedRequestOptionsInit, "method" | "data">
112-
): Promise<string> {
113-
const file = encodeURI(filePath)
108+
): Promise<RequestResponse<PresignedResult & ApplicationError>> {
109+
const file = encodeURI(filePath);
114110
const requestOptions = { ...(resOptions || {}), method: "POST" };
115-
const { response, data } = await this.request<SimpleStringValue>(`${this.options.genUrl}?key=${file}`, requestOptions);
116-
if (response.ok) {
117-
return data.value;
118-
} else {
119-
return "";
120-
}
111+
const { response, data } = await this.request<SimpleStringValue & ApplicationError>(
112+
`${this.options.genUrl}?key=${file}`,
113+
requestOptions
114+
);
115+
return { data: { url: (data?.value || "") }, response }
121116
}
122117

123118
private putObjectAsync(
124119
client: Minio.Client,
125120
bucketName: string,
126121
objectName: string,
127-
stream: any): Promise<RequestResponse<UploadResult>> {
122+
stream: any
123+
): Promise<RequestResponse<UploadResult>> {
128124
return new Promise((resolve, reject) => {
129125
client.putObject(bucketName, objectName, stream, (err, etag) => {
130126
if (err === undefined || err === null) {
131-
resolve(
132-
{ data: { etag }, response: { ok: true, status: 200, type:"default"} as any }
133-
);
127+
resolve({ data: { etag }, response: { ok: true, status: 200, type: "default" } as any });
134128
} else {
135-
const data: UploadResult = {etag};
136-
if((typeof err) ==="string"){
129+
const data: UploadResult = { etag };
130+
if (typeof err === "string") {
137131
data.error = err as any;
138132
data.error_description = err as any;
139-
}else{
133+
} else {
140134
data.error = err?.name;
141-
data.error_description = err?.message
135+
data.error_description = err?.message;
142136
}
143-
144-
reject({data, response: { ok: false, status: 500 } as any});
137+
138+
reject({ data, response: { ok: false, status: 500 } as any });
145139
}
146140
});
147141
});
148142
}
149143

150-
151-
public async upload(
152-
bucketPolicy: BucketPolicy,
153-
key: string,
154-
stream: any
155-
): Promise<RequestResponse<UploadResult>> {
156-
144+
public async upload(bucketPolicy: BucketPolicy, key: string, stream: any): Promise<RequestResponse<UploadResult>> {
157145
const r = await this.getMinioContext();
158146

159-
const {response, data } = r;
147+
const { response, data } = r;
160148
if (!r.response.ok) {
161-
return { data: data as any, response }
149+
return { data: data as any, response };
162150
}
163151

164152
const { stsToken, config } = r.data;
165-
const cnf = config as MinioConfig
153+
const cnf = config as MinioConfig;
166154

167155
const bucketName = bucketPolicy === BucketPolicy.Private ? cnf.privateBucket : cnf.publicBucket;
168156

169157
const minioClient = new Minio.Client({
170158
endPoint: cnf.host,
171159
port: cnf.port,
172160
region: cnf.region,
173-
useSSL: (cnf.schema === "https"),
161+
useSSL: cnf.schema === "https",
174162
accessKey: stsToken?.accessKey || "",
175163
secretKey: stsToken?.secretKey || ""
176164
});
177165

178-
return await this.putObjectAsync(minioClient, bucketName, key, stream)
179-
};
180-
181-
}
166+
return await this.putObjectAsync(minioClient, bucketName, key, stream);
167+
}
168+
}

src/minio/types.ts

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,4 +21,8 @@ export interface AssumedCredentials {
2121

2222
export interface UploadResult extends ApplicationError {
2323
etag: string;
24-
}
24+
}
25+
26+
export interface PresignedResult {
27+
url: string;
28+
}

src/oauth2/session.ts

Lines changed: 11 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -24,11 +24,11 @@ const anonymousPrincipal: UserPrincipal = {
2424
};
2525

2626
function tokenToPrincipal(token: OAuth2AccessToken): UserPrincipal {
27-
const roles:string[] = [];
28-
const attributes:{ [name:string]:string } = {};
27+
const roles: string[] = [];
28+
const attributes: { [name: string]: string } = {};
2929

30-
for(const r in token.authorities){
31-
if(r.indexOf("ROLE_") === 0){
30+
for (const r in token.authorities) {
31+
if (r.indexOf("ROLE_") === 0) {
3232
roles.push(r);
3333
}
3434
}
@@ -46,9 +46,9 @@ function tokenToPrincipal(token: OAuth2AccessToken): UserPrincipal {
4646
"username"
4747
];
4848

49-
for(const att in token){
50-
if(wellknownProperties.indexOf(att) < 0){
51-
attributes[att] = token[att]
49+
for (const att in token) {
50+
if (wellknownProperties.indexOf(att) < 0) {
51+
attributes[att] = token[att];
5252
}
5353
}
5454

@@ -73,7 +73,7 @@ function tokenToPrincipal(token: OAuth2AccessToken): UserPrincipal {
7373
return this.token?.two_factor_granted;
7474
},
7575

76-
get attachedAttributes():{ [name:string]:string } {
76+
get attachedAttributes(): { [name: string]: string } {
7777
return this.attributes;
7878
},
7979

@@ -82,11 +82,11 @@ function tokenToPrincipal(token: OAuth2AccessToken): UserPrincipal {
8282
},
8383

8484
get isAnonymous(): boolean {
85-
return isNullOrEmptyString(this.token?.user_id)
85+
return isNullOrEmptyString(this.token?.user_id);
8686
},
8787

8888
hasRole(role: string): boolean {
89-
return isNullOrEmptyString(this.roles?.find(item => item === role));
89+
return isNullOrEmptyString(this.roles?.find((item) => item === role));
9090
},
9191

9292
hasAnyOfRoles(...roleNames: string[]): boolean {
@@ -100,12 +100,10 @@ function tokenToPrincipal(token: OAuth2AccessToken): UserPrincipal {
100100
}
101101
return false;
102102
}
103-
}
103+
};
104104
return p;
105-
106105
}
107106

108-
109107
function createPrincipal(accessToken?: OAuth2AccessToken): UserPrincipal {
110108
return accessToken ? tokenToPrincipal(accessToken) : anonymousPrincipal;
111109
}

src/oauth2/types.ts

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,10 @@
1-
21
export interface UserPrincipal {
32
userId?: string;
43
userName?: string;
54
authorities?: string[];
65
isTwoFactorGranted?: boolean;
76
isAnonymous: boolean;
8-
attachedAttributes: { [name:string]:string };
7+
attachedAttributes: { [name: string]: string };
98

109
getRoles(): string[];
1110
hasRole(role: string): boolean;

src/request/index.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import {
44
ResponseError,
55
RequestMethod,
66
RequestOptionsInit,
7-
RequestResponse,
7+
RequestResponse
88
} from "umi-request";
99
import { RefreshTokenParam, OAuth2AccessToken, GrantTypes, LoginParam, CheckTokenResult } from "../oauth2";
1010
import { ErrorContext, CustomErrorHandler, RequestOptions } from "./types";
@@ -51,8 +51,8 @@ const handleError = (error: ResponseError, options: RequestOptions, skipNotify?:
5151
const handlers: CustomErrorHandler[] = options.errorHandlers || [];
5252
if (handlers.length) {
5353
const errCtx: ErrorContext = { error, options, skipNotify };
54-
const handled = handlers.some(v => {
55-
v.handle(errCtx)
54+
const handled = handlers.some((v) => {
55+
v.handle(errCtx);
5656
});
5757
if (handled) {
5858
return;
@@ -132,7 +132,7 @@ export function initRequest(options: RequestOptions, session?: OAuth2Session): E
132132
request.use(async (ctx, next) => {
133133
const op = ctx && ctx.req ? (ctx.req.options as ExtendedRequestOptionsInit) : undefined;
134134
if (op && typeof op.errorHandler === "undefined") {
135-
op.errorHandler = e => handleError(e, options, op.skipNotifyError);
135+
op.errorHandler = (e) => handleError(e, options, op.skipNotifyError);
136136
}
137137

138138
if (op && op.skipAuth !== true && requestContext.session && requestContext.session.isLogged) {

src/request/types.ts

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,16 @@
11
import { ResponseError } from "umi-request";
22
import { ToastAdapter } from "../core";
33

4-
export interface ErrorContext{
4+
export interface ErrorContext {
55
error: ResponseError;
6-
options: RequestOptions;
6+
options: RequestOptions;
77
skipNotify?: boolean;
88
}
99

10-
export interface CustomErrorHandler{
10+
export interface CustomErrorHandler {
1111
handle(context: ErrorContext): boolean;
1212
}
1313

14-
1514
export interface RequestOptions {
1615
clientId: string;
1716
clientSecret: string;

src/utils/index.ts

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,13 @@
11
import moment, { Moment } from "moment";
22

33
/* eslint no-useless-escape:0 import/prefer-default-export:0 */
4-
const regexUrl = /(((^https?:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+(?::\d+)?|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)$/;
5-
const regexEmail = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
4+
const regexUrl =
5+
/(((^https?:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+(?::\d+)?|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)$/;
6+
const regexEmail =
7+
/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
68
const regexPositiveNumber = /^([0]*[1-9][0-9]*)(\.[0-9]*)?$/;
7-
const regexChineseMobileNumber = /^((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|(166)|(17[0,1,3,5,6,7,8])|(18[0-9])|(19[8|9]))\d{8}$/;
9+
const regexChineseMobileNumber =
10+
/^((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|(166)|(17[0,1,3,5,6,7,8])|(18[0-9])|(19[8|9]))\d{8}$/;
811

912
export const isUrl = (path: string): boolean => regexUrl.test(path);
1013
export const isEmail = (path: string): boolean => regexEmail.test(path);
@@ -20,7 +23,7 @@ export const notNullOrEmptyString = (value?: any) => !isNullOrEmptyString(value)
2023

2124
export function generateUUID() {
2225
let d = new Date().getTime();
23-
const uuid = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, c => {
26+
const uuid = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
2427
const r = (d + Math.random() * 16) % 16 | 0;
2528
d = Math.floor(d / 16);
2629
return (c === "x" ? r : (r & 0x3) | 0x8).toString(16);

0 commit comments

Comments
 (0)