R.allPass/anyPassを使用して、複数の条件を検証するIf文を回避
2100 ワード
Node:次の検証タイプの関数を実装します.主な検証:およびこのファイルが存在するかどうか アップロードされたファイルがxlsxファイルフォーマット であるかどうかファイルサイズ<8 M フロントエンドでアップロードされたフォーム名が「xlsxfile」のファイル 条件が一致している場合にのみ、
前提条件が既知であるはmulterミドルウェアを使用し、アップロードされたfileは のデータ構造を返す.
一般的な書き方息抜きの書き方: n連発if判断書き方:
優雅な書き方
R.allPassメソッドの使用
True
の値が返されます.前提条件が既知である
#
const file = {
fieldname: 'xlsxfile',
originalname: 'Y~Z.xlsx',
encoding: '7bit',
mimetype:
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
destination: 'D:\\Code\\upload_TEMP',
filename: 'data.xlsx',
path: 'D:\\Code\\upload_TEMP\\data.xlsx',
size: 9848,
};
一般的な書き方
import {existsSync} from 'fs';
const validate =(file)=>{
const xlsxMIME =
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
if(existsSync(file)&&file.mimetype===xlsxMIME&&file.size<=8*1024*1024&&file.fieldname!=='xlsxfile'){
return true;
}
return false;
}
import {existsSync} from 'fs';
const validate =(file)=>{
const xlsxMIME =
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
if(!existsSync(file)){
return false;
}
if(file.mimetype!==xlsxMIME){
return false;
}
if(file.size>=8*1024*1024){
return false;
}
if(file.fieldname!=='xlsxfile'){
return false;
}
return true;
}
優雅な書き方
R.allPassメソッドの使用
import { existsSync } from 'fs';
const validate = (file) => {
const xlsxMIME =
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
const validRules = [
(file) => existsSync(file.path),
(file) => file.mimetype === xlsxMIME,
(file) => file.size<=8*1024*1024,
(file) => file.fieldname === 'xlsxfile'
];
return R.allPass(validRules)(file);
};