Skip to content

Commit

Permalink
pretty code
Browse files Browse the repository at this point in the history
  • Loading branch information
endink committed May 13, 2021
1 parent bb33308 commit 1aecefd
Show file tree
Hide file tree
Showing 10 changed files with 64 additions and 76 deletions.
4 changes: 2 additions & 2 deletions src/aliyun/oss.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ export class OssUtils {
if (!config.response.ok) {
return config as any;
}

if (aliyunContext.stsToken === undefined || Number(aliyunContext.stsToken.expiration) <= Date.now().valueOf()) {
const r = await this.request<AliyunStsToken>(this.options.stsTokenURL, {
method: "GET",
Expand All @@ -83,7 +83,7 @@ export class OssUtils {
return r as any; // 发生错误,类型无所谓
}
}

return { data: aliyunContext, response: { ok: true } } as any;
}

Expand Down
3 changes: 1 addition & 2 deletions src/aliyun/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,5 @@ export interface AliyunOssConfig {
}

export interface AliyunConfig {
oss: AliyunOssConfig
oss: AliyunOssConfig;
}

1 change: 0 additions & 1 deletion src/minio/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,3 @@ import { MinioUtils } from "./minio";

export * from "./types";
export * from "./minio";

73 changes: 30 additions & 43 deletions src/minio/minio.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { AssumedCredentials, MinioConfig } from ".";
import { ExtendedRequestMethod, ExtendedRequestOptionsInit } from "../request";
import { ApplicationError, BucketPolicy } from "../core";
import * as Minio from "minio";
import { UploadResult } from "./types";
import { PresignedResult, UploadResult } from "./types";

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

type SimpleStringValue = {
value: string
}
value: string;
};

export class MinioUtils {
private constructor(private request: ExtendedRequestMethod, public options: MinioOptions) {

}
private constructor(private request: ExtendedRequestMethod, public options: MinioOptions) {}

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

if (minioContext.stsToken === undefined || (minioContext.tokenTime + durationMills) <= Date.now().valueOf()) {
if (minioContext.stsToken === undefined || minioContext.tokenTime + durationMills <= Date.now().valueOf()) {
const r = await this.request<AssumedCredentials>(this.options.stsTokenURL, {
method: "POST",
skipNotifyError: true
});
if (r.response.ok) {
minioContext.stsToken = r.data;
minioContext.tokenTime = Date.now().valueOf()
minioContext.tokenTime = Date.now().valueOf();
} else {
return r as any; // 发生错误,类型无所谓
}
Expand All @@ -92,11 +90,9 @@ export class MinioUtils {
return { data: minioContext, response: { ok: true } } as any;
}


public generateObjectUrl(key: string): string | undefined {
const config = minioContext.config;
if (config && !isNullOrEmptyString(config.publicBucket)) {

const file = key.startsWith("/") ? key.substr(1, key.length - 1) : key;
if (config.port) {
return `${config.schema}://${config.host}:${config.port}/${config.publicBucket}/${file}`;
Expand All @@ -109,73 +105,64 @@ export class MinioUtils {
public async presignedObjectUrl(
filePath: string,
resOptions?: Omit<ExtendedRequestOptionsInit, "method" | "data">
): Promise<string> {
const file = encodeURI(filePath)
): Promise<RequestResponse<PresignedResult & ApplicationError>> {
const file = encodeURI(filePath);
const requestOptions = { ...(resOptions || {}), method: "POST" };
const { response, data } = await this.request<SimpleStringValue>(`${this.options.genUrl}?key=${file}`, requestOptions);
if (response.ok) {
return data.value;
} else {
return "";
}
const { response, data } = await this.request<SimpleStringValue & ApplicationError>(
`${this.options.genUrl}?key=${file}`,
requestOptions
);
return { data: { url: (data?.value || "") }, response }
}

private putObjectAsync(
client: Minio.Client,
bucketName: string,
objectName: string,
stream: any): Promise<RequestResponse<UploadResult>> {
stream: any
): Promise<RequestResponse<UploadResult>> {
return new Promise((resolve, reject) => {
client.putObject(bucketName, objectName, stream, (err, etag) => {
if (err === undefined || err === null) {
resolve(
{ data: { etag }, response: { ok: true, status: 200, type:"default"} as any }
);
resolve({ data: { etag }, response: { ok: true, status: 200, type: "default" } as any });
} else {
const data: UploadResult = {etag};
if((typeof err) ==="string"){
const data: UploadResult = { etag };
if (typeof err === "string") {
data.error = err as any;
data.error_description = err as any;
}else{
} else {
data.error = err?.name;
data.error_description = err?.message
data.error_description = err?.message;
}
reject({data, response: { ok: false, status: 500 } as any});

reject({ data, response: { ok: false, status: 500 } as any });
}
});
});
}


public async upload(
bucketPolicy: BucketPolicy,
key: string,
stream: any
): Promise<RequestResponse<UploadResult>> {

public async upload(bucketPolicy: BucketPolicy, key: string, stream: any): Promise<RequestResponse<UploadResult>> {
const r = await this.getMinioContext();

const {response, data } = r;
const { response, data } = r;
if (!r.response.ok) {
return { data: data as any, response }
return { data: data as any, response };
}

const { stsToken, config } = r.data;
const cnf = config as MinioConfig
const cnf = config as MinioConfig;

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

const minioClient = new Minio.Client({
endPoint: cnf.host,
port: cnf.port,
region: cnf.region,
useSSL: (cnf.schema === "https"),
useSSL: cnf.schema === "https",
accessKey: stsToken?.accessKey || "",
secretKey: stsToken?.secretKey || ""
});

return await this.putObjectAsync(minioClient, bucketName, key, stream)
};

}
return await this.putObjectAsync(minioClient, bucketName, key, stream);
}
}
6 changes: 5 additions & 1 deletion src/minio/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,8 @@ export interface AssumedCredentials {

export interface UploadResult extends ApplicationError {
etag: string;
}
}

export interface PresignedResult {
url: string;
}
24 changes: 11 additions & 13 deletions src/oauth2/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,11 @@ const anonymousPrincipal: UserPrincipal = {
};

function tokenToPrincipal(token: OAuth2AccessToken): UserPrincipal {
const roles:string[] = [];
const attributes:{ [name:string]:string } = {};
const roles: string[] = [];
const attributes: { [name: string]: string } = {};

for(const r in token.authorities){
if(r.indexOf("ROLE_") === 0){
for (const r in token.authorities) {
if (r.indexOf("ROLE_") === 0) {
roles.push(r);
}
}
Expand All @@ -46,9 +46,9 @@ function tokenToPrincipal(token: OAuth2AccessToken): UserPrincipal {
"username"
];

for(const att in token){
if(wellknownProperties.indexOf(att) < 0){
attributes[att] = token[att]
for (const att in token) {
if (wellknownProperties.indexOf(att) < 0) {
attributes[att] = token[att];
}
}

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

get attachedAttributes():{ [name:string]:string } {
get attachedAttributes(): { [name: string]: string } {
return this.attributes;
},

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

get isAnonymous(): boolean {
return isNullOrEmptyString(this.token?.user_id)
return isNullOrEmptyString(this.token?.user_id);
},

hasRole(role: string): boolean {
return isNullOrEmptyString(this.roles?.find(item => item === role));
return isNullOrEmptyString(this.roles?.find((item) => item === role));
},

hasAnyOfRoles(...roleNames: string[]): boolean {
Expand All @@ -100,12 +100,10 @@ function tokenToPrincipal(token: OAuth2AccessToken): UserPrincipal {
}
return false;
}
}
};
return p;

}


function createPrincipal(accessToken?: OAuth2AccessToken): UserPrincipal {
return accessToken ? tokenToPrincipal(accessToken) : anonymousPrincipal;
}
Expand Down
3 changes: 1 addition & 2 deletions src/oauth2/types.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@

export interface UserPrincipal {
userId?: string;
userName?: string;
authorities?: string[];
isTwoFactorGranted?: boolean;
isAnonymous: boolean;
attachedAttributes: { [name:string]:string };
attachedAttributes: { [name: string]: string };

getRoles(): string[];
hasRole(role: string): boolean;
Expand Down
8 changes: 4 additions & 4 deletions src/request/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import {
ResponseError,
RequestMethod,
RequestOptionsInit,
RequestResponse,
RequestResponse
} from "umi-request";
import { RefreshTokenParam, OAuth2AccessToken, GrantTypes, LoginParam, CheckTokenResult } from "../oauth2";
import { ErrorContext, CustomErrorHandler, RequestOptions } from "./types";
Expand Down Expand Up @@ -51,8 +51,8 @@ const handleError = (error: ResponseError, options: RequestOptions, skipNotify?:
const handlers: CustomErrorHandler[] = options.errorHandlers || [];
if (handlers.length) {
const errCtx: ErrorContext = { error, options, skipNotify };
const handled = handlers.some(v => {
v.handle(errCtx)
const handled = handlers.some((v) => {
v.handle(errCtx);
});
if (handled) {
return;
Expand Down Expand Up @@ -132,7 +132,7 @@ export function initRequest(options: RequestOptions, session?: OAuth2Session): E
request.use(async (ctx, next) => {
const op = ctx && ctx.req ? (ctx.req.options as ExtendedRequestOptionsInit) : undefined;
if (op && typeof op.errorHandler === "undefined") {
op.errorHandler = e => handleError(e, options, op.skipNotifyError);
op.errorHandler = (e) => handleError(e, options, op.skipNotifyError);
}

if (op && op.skipAuth !== true && requestContext.session && requestContext.session.isLogged) {
Expand Down
7 changes: 3 additions & 4 deletions src/request/types.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,16 @@
import { ResponseError } from "umi-request";
import { ToastAdapter } from "../core";

export interface ErrorContext{
export interface ErrorContext {
error: ResponseError;
options: RequestOptions;
options: RequestOptions;
skipNotify?: boolean;
}

export interface CustomErrorHandler{
export interface CustomErrorHandler {
handle(context: ErrorContext): boolean;
}


export interface RequestOptions {
clientId: string;
clientSecret: string;
Expand Down
11 changes: 7 additions & 4 deletions src/utils/index.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
import moment, { Moment } from "moment";

/* eslint no-useless-escape:0 import/prefer-default-export:0 */
const regexUrl = /(((^https?:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+(?::\d+)?|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)$/;
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,}))$/;
const regexUrl =
/(((^https?:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+(?::\d+)?|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)$/;
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,}))$/;
const regexPositiveNumber = /^([0]*[1-9][0-9]*)(\.[0-9]*)?$/;
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}$/;
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}$/;

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

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

0 comments on commit 1aecefd

Please sign in to comment.