How to use realContentType method in apickli

Best JavaScript code snippet using apickli

converters.ts

Source:converters.ts Github

copy

Full Screen

1import {buildGqlSelectionInfos, replaceVars} from "./utils";2export const upper = () => v => `${v}`.toUpperCase();3export const lower = () => v => `${v}`.toLowerCase();4export const jsonParse = () => v => v ? JSON.parse(v) : undefined;5export const s3file_content = () => async v => v ? require('@ohoareau/aws').s3.getFileContent(v) : undefined;6export const s3file_hash = ({algorithm = 'md5'}) => async v => v ? require('./services/crypto').default.hash(await require('@ohoareau/aws').s3.getFileContent(v), algorithm) : undefined;7export const s3file_fingerprint = ({algorithm = 'sha256'}) => async v => v ? require('./services/crypto').default.hash(await require('@ohoareau/aws').s3.getFileContent(v), algorithm) : undefined;8export const s3file_url = () => async v => v ? (await require('@ohoareau/aws').s3.getFileViewUrl(v)).viewUrl : undefined;9export const s3file_url_infos = () => async v => v ? require('@ohoareau/aws').s3.getFileViewUrl(v) : undefined;10export const s3file_url_view = () => async v => v ? (await require('@ohoareau/aws').s3.getFileViewUrl(v)).viewUrl : undefined;11export const s3file_url_view_infos = () => async v => v ? require('@ohoareau/aws').s3.getFileViewUrl(v) : undefined;12export const s3file_url_dl = () => async v => v ? (await require('@ohoareau/aws').s3.getFileDownloadUrl(v)).downloadUrl : undefined;13export const s3file_url_dl_infos = () => async v => v ? require('@ohoareau/aws').s3.getFileDownloadUrl(v) : undefined;14export const s3file_url_ul = () => async v => v ? (await require('@ohoareau/aws').s3.getFileUploadUrl(v)).uploadUrl : undefined;15export const s3file_url_ul_infos = () => async v => v ? require('@ohoareau/aws').s3.getFileUploadUrl(v) : undefined;16export const image = ({bucket: archiveBucket, key: archiveKey, name: archiveName, attribute, urlPattern}) => async (v, result, query) => {17 const x = {available: false};18 if (v && v.fingerprint) x.available = true;19 const vars = {...query, ...(query.oldData || {}), ...(query.data || {}), ...result};20 if (!x.available) {21 archiveBucket = replaceVars(archiveBucket, vars)22 archiveKey = replaceVars(archiveKey, vars);23 archiveName = archiveName ? replaceVars(archiveName, vars) : undefined;24 }25 const [selection, selected] = buildGqlSelectionInfos(query, attribute);26 const s3 = require('@ohoareau/aws').s3;27 const cdnObject = (x.available && process.env.PUBLIC_IMAGE_BUCKET_NAME)28 ? {29 bucket: process.env.PUBLIC_IMAGE_BUCKET_NAME || undefined,30 key: process.env.PUBLIC_IMAGE_BUCKET_NAME ? await buildPublicImageBucketKey(v['fingerprint']) : undefined,31 contentType: v['contentType'],32 name: v['name'],33 }34 : {}35 ;36 const vv = x.available ? {37 bucket: cdnObject.bucket || v['bucket'],38 key: cdnObject.key || v['key'],39 contentType: v['contentType'],40 name: v['name'],41 } : {42 bucket: archiveBucket,43 key: archiveKey,44 name: archiveName,45 };46 if (x.available) {47 await Promise.all(selected.map(async k => {48 switch (k) {49 case 'bucket': x['bucket'] = v['bucket']; break;50 case 'cdnBucket': x['cdnBucket'] = cdnObject['bucket']; break;51 case 'key': x['key'] = v['key']; break;52 case 'cdnKey': x['cdnKey'] = cdnObject['key']; break;53 case 'name': x['name'] = v['name']; break;54 case 'contentType': x['contentType'] = v['contentType']; break;55 case 'fingerprint': x['fingerprint'] = v['fingerprint']; break;56 case 'content': x['content'] = await s3.getFileContent(vv); break;57 case 'contentAsBase64': x['contentAsBase64'] = Buffer.from(await s3.getFileContent(vv), 'utf-8').toString('base64'); break;58 case 'contentAsBase64Url': x['contentAsBase64Url'] = Buffer.from(await s3.getFileContent(vv), 'utf-8').toString('base64url'); break;59 case 'cdnUrl': x['cdnUrl'] = cdnObject ? await buildImageCdnUrl({...(cdnObject || {}), fingerprint: v['fingerprint']} as any, selection[k]) : undefined; break;60 case 'url': x['url'] = urlPattern ? buildUrlFromPattern(urlPattern, vars, v) : (await s3.getFileViewUrl(vv)).viewUrl; break;61 case 'urlInfos': x['urlInfos'] = await s3.getFileViewUrl(vv); break;62 case 'viewUrl': x['viewUrl'] = (await s3.getFileViewUrl(vv)).viewUrl; break;63 case 'viewUrlInfos': x['viewUrlInfos'] = await s3.getFileViewUrl(vv); break;64 case 'downloadUrl': x['downloadUrl'] = (await s3.getFileDownloadUrl(vv)).downloadUrl; break;65 case 'downloadUrlInfos': x['downloadUrlInfos'] = await s3.getFileDownloadUrl(vv); break;66 case 'uploadUrl': x['uploadUrl'] = (await s3.getFileUploadUrl(vv)).uploadUrl; break;67 case 'uploadUrlInfos': x['uploadUrlInfos'] = await s3.getFileUploadUrl(vv); break;68 case 'size':69 case 'realContentType':70 case 'eTag':71 case 'lastModified':72 const metadata = await s3.getFileMetadata(vv);73 switch (k) {74 case 'size': x['size'] = metadata.contentLength; break;75 case 'realContentType': x['realContentType'] = metadata.contentType; break;76 case 'eTag': x['eTag'] = metadata.eTag; break;77 case 'lastModified': x['lastModified'] = metadata.lastModified.getTime(); break;78 default: break;79 }80 break;81 default: break;82 }83 }));84 } else {85 await Promise.all(selected.map(async k => {86 switch (k) {87 case 'bucket': x['bucket'] = vv['bucket']; break;88 case 'key': x['key'] = vv['key']; break;89 case 'name': x['name'] = vv['name']; break;90 case 'uploadUrl': x['uploadUrl'] = (await s3.getFileUploadUrl(vv)).uploadUrl; break;91 case 'uploadUrlInfos': x['uploadUrlInfos'] = await s3.getFileUploadUrl(vv); break;92 default: break;93 }94 }));95 }96 return x;97}98export const css = ({bucket: archiveBucket, key: archiveKey, name: archiveName, attribute, urlPattern}) => async (v, result, query) => {99 const x = {available: false};100 if (v && v.fingerprint) x.available = true;101 const vars = {...query, ...(query.oldData || {}), ...(query.data || {}), ...result};102 if (!x.available) {103 archiveBucket = replaceVars(archiveBucket, vars)104 archiveKey = replaceVars(archiveKey, vars);105 archiveName = archiveName ? replaceVars(archiveName, vars) : undefined;106 }107 const [selection, selected] = buildGqlSelectionInfos(query, attribute);108 const s3 = require('@ohoareau/aws').s3;109 const cdnObject = (x.available && process.env.PUBLIC_CSS_BUCKET_NAME)110 ? {111 bucket: process.env.PUBLIC_CSS_BUCKET_NAME || undefined,112 key: process.env.PUBLIC_CSS_BUCKET_NAME ? await buildPublicCssBucketKey(v['fingerprint']) : undefined,113 contentType: v['contentType'],114 name: v['name'],115 }116 : {}117 ;118 const vv = x.available ? {119 bucket: cdnObject.bucket || v['bucket'],120 key: cdnObject.key || v['key'],121 contentType: v['contentType'],122 name: v['name'],123 } : {124 bucket: archiveBucket,125 key: archiveKey,126 name: archiveName,127 };128 if (x.available) {129 await Promise.all(selected.map(async k => {130 switch (k) {131 case 'bucket': x['bucket'] = v['bucket']; break;132 case 'cdnBucket': x['cdnBucket'] = cdnObject['bucket']; break;133 case 'key': x['key'] = v['key']; break;134 case 'cdnKey': x['cdnKey'] = cdnObject['key']; break;135 case 'name': x['name'] = v['name']; break;136 case 'contentType': x['contentType'] = v['contentType']; break;137 case 'fingerprint': x['fingerprint'] = v['fingerprint']; break;138 case 'content': x['content'] = await s3.getFileContent(vv); break;139 case 'contentAsBase64': x['contentAsBase64'] = Buffer.from(await s3.getFileContent(vv), 'utf-8').toString('base64'); break;140 case 'contentAsBase64Url': x['contentAsBase64Url'] = Buffer.from(await s3.getFileContent(vv), 'utf-8').toString('base64url'); break;141 case 'cdnUrl': x['cdnUrl'] = cdnObject ? await buildImageCdnUrl({...(cdnObject || {}), fingerprint: v['fingerprint']} as any, selection[k]) : undefined; break;142 case 'url': x['url'] = urlPattern ? buildUrlFromPattern(urlPattern, vars, v) : (await s3.getFileViewUrl(vv)).viewUrl; break;143 case 'urlInfos': x['urlInfos'] = await s3.getFileViewUrl(vv); break;144 case 'viewUrl': x['viewUrl'] = (await s3.getFileViewUrl(vv)).viewUrl; break;145 case 'viewUrlInfos': x['viewUrlInfos'] = await s3.getFileViewUrl(vv); break;146 case 'downloadUrl': x['downloadUrl'] = (await s3.getFileDownloadUrl(vv)).downloadUrl; break;147 case 'downloadUrlInfos': x['downloadUrlInfos'] = await s3.getFileDownloadUrl(vv); break;148 case 'uploadUrl': x['uploadUrl'] = (await s3.getFileUploadUrl(vv)).uploadUrl; break;149 case 'uploadUrlInfos': x['uploadUrlInfos'] = await s3.getFileUploadUrl(vv); break;150 case 'size':151 case 'realContentType':152 case 'eTag':153 case 'lastModified':154 const metadata = await s3.getFileMetadata(vv);155 switch (k) {156 case 'size': x['size'] = metadata.contentLength; break;157 case 'realContentType': x['realContentType'] = metadata.contentType; break;158 case 'eTag': x['eTag'] = metadata.eTag; break;159 case 'lastModified': x['lastModified'] = metadata.lastModified.getTime(); break;160 default: break;161 }162 break;163 default: break;164 }165 }));166 } else {167 await Promise.all(selected.map(async k => {168 switch (k) {169 case 'bucket': x['bucket'] = vv['bucket']; break;170 case 'key': x['key'] = vv['key']; break;171 case 'name': x['name'] = vv['name']; break;172 case 'uploadUrl': x['uploadUrl'] = (await s3.getFileUploadUrl(vv)).uploadUrl; break;173 case 'uploadUrlInfos': x['uploadUrlInfos'] = await s3.getFileUploadUrl(vv); break;174 default: break;175 }176 }));177 }178 return x;179}180export const js = ({bucket: archiveBucket, key: archiveKey, name: archiveName, attribute, urlPattern}) => async (v, result, query) => {181 const x = {available: false};182 if (v && v.fingerprint) x.available = true;183 const vars = {...query, ...(query.oldData || {}), ...(query.data || {}), ...result};184 if (!x.available) {185 archiveBucket = replaceVars(archiveBucket, vars)186 archiveKey = replaceVars(archiveKey, vars);187 archiveName = archiveName ? replaceVars(archiveName, vars) : undefined;188 }189 const [selection, selected] = buildGqlSelectionInfos(query, attribute);190 const s3 = require('@ohoareau/aws').s3;191 const cdnObject = (x.available && process.env.PUBLIC_JS_BUCKET_NAME)192 ? {193 bucket: process.env.PUBLIC_JS_BUCKET_NAME || undefined,194 key: process.env.PUBLIC_JS_BUCKET_NAME ? await buildPublicJsBucketKey(v['fingerprint']) : undefined,195 contentType: v['contentType'],196 name: v['name'],197 }198 : {}199 ;200 const vv = x.available ? {201 bucket: cdnObject.bucket || v['bucket'],202 key: cdnObject.key || v['key'],203 contentType: v['contentType'],204 name: v['name'],205 } : {206 bucket: archiveBucket,207 key: archiveKey,208 name: archiveName,209 };210 if (x.available) {211 await Promise.all(selected.map(async k => {212 switch (k) {213 case 'bucket': x['bucket'] = v['bucket']; break;214 case 'cdnBucket': x['cdnBucket'] = cdnObject['bucket']; break;215 case 'key': x['key'] = v['key']; break;216 case 'cdnKey': x['cdnKey'] = cdnObject['key']; break;217 case 'name': x['name'] = v['name']; break;218 case 'contentType': x['contentType'] = v['contentType']; break;219 case 'fingerprint': x['fingerprint'] = v['fingerprint']; break;220 case 'content': x['content'] = await s3.getFileContent(vv); break;221 case 'contentAsBase64': x['contentAsBase64'] = Buffer.from(await s3.getFileContent(vv), 'utf-8').toString('base64'); break;222 case 'contentAsBase64Url': x['contentAsBase64Url'] = Buffer.from(await s3.getFileContent(vv), 'utf-8').toString('base64url'); break;223 case 'cdnUrl': x['cdnUrl'] = cdnObject ? await buildImageCdnUrl({...(cdnObject || {}), fingerprint: v['fingerprint']} as any, selection[k]) : undefined; break;224 case 'url': x['url'] = urlPattern ? buildUrlFromPattern(urlPattern, vars, v) : (await s3.getFileViewUrl(vv)).viewUrl; break;225 case 'urlInfos': x['urlInfos'] = await s3.getFileViewUrl(vv); break;226 case 'viewUrl': x['viewUrl'] = (await s3.getFileViewUrl(vv)).viewUrl; break;227 case 'viewUrlInfos': x['viewUrlInfos'] = await s3.getFileViewUrl(vv); break;228 case 'downloadUrl': x['downloadUrl'] = (await s3.getFileDownloadUrl(vv)).downloadUrl; break;229 case 'downloadUrlInfos': x['downloadUrlInfos'] = await s3.getFileDownloadUrl(vv); break;230 case 'uploadUrl': x['uploadUrl'] = (await s3.getFileUploadUrl(vv)).uploadUrl; break;231 case 'uploadUrlInfos': x['uploadUrlInfos'] = await s3.getFileUploadUrl(vv); break;232 case 'size':233 case 'realContentType':234 case 'eTag':235 case 'lastModified':236 const metadata = await s3.getFileMetadata(vv);237 switch (k) {238 case 'size': x['size'] = metadata.contentLength; break;239 case 'realContentType': x['realContentType'] = metadata.contentType; break;240 case 'eTag': x['eTag'] = metadata.eTag; break;241 case 'lastModified': x['lastModified'] = metadata.lastModified.getTime(); break;242 default: break;243 }244 break;245 default: break;246 }247 }));248 } else {249 await Promise.all(selected.map(async k => {250 switch (k) {251 case 'bucket': x['bucket'] = vv['bucket']; break;252 case 'key': x['key'] = vv['key']; break;253 case 'name': x['name'] = vv['name']; break;254 case 'uploadUrl': x['uploadUrl'] = (await s3.getFileUploadUrl(vv)).uploadUrl; break;255 case 'uploadUrlInfos': x['uploadUrlInfos'] = await s3.getFileUploadUrl(vv); break;256 default: break;257 }258 }));259 }260 return x;261}262export const file = ({bucket: archiveBucket, key: archiveKey, name: archiveName, attribute, urlPattern}) => async (v, result, query) => {263 const x = {available: false};264 if (v && v.fingerprint) x.available = true;265 const vars = {...query, ...(query.oldData || {}), ...(query.data || {}), ...result};266 if (!x.available) {267 archiveBucket = replaceVars(archiveBucket, vars)268 archiveKey = replaceVars(archiveKey, vars);269 archiveName = archiveName ? replaceVars(archiveName, vars) : undefined;270 }271 const [selection, selected] = buildGqlSelectionInfos(query, attribute);272 const s3 = require('@ohoareau/aws').s3;273 const cdnObject = (x.available && process.env.PUBLIC_FILE_BUCKET_NAME)274 ? {275 bucket: process.env.PUBLIC_FILE_BUCKET_NAME || undefined,276 key: process.env.PUBLIC_FILE_BUCKET_NAME ? await buildPublicFileBucketKey(v['fingerprint']) : undefined,277 contentType: v['contentType'],278 name: v['name'],279 }280 : {}281 ;282 const vv = x.available ? {283 bucket: cdnObject.bucket || v['bucket'],284 key: cdnObject.key || v['key'],285 contentType: v['contentType'],286 name: v['name'],287 } : {288 bucket: archiveBucket,289 key: archiveKey,290 name: archiveName,291 };292 if (x.available) {293 await Promise.all(selected.map(async k => {294 switch (k) {295 case 'bucket': x['bucket'] = v['bucket']; break;296 case 'cdnBucket': x['cdnBucket'] = cdnObject['bucket']; break;297 case 'key': x['key'] = v['key']; break;298 case 'cdnKey': x['cdnKey'] = cdnObject['key']; break;299 case 'name': x['name'] = v['name']; break;300 case 'contentType': x['contentType'] = v['contentType']; break;301 case 'fingerprint': x['fingerprint'] = v['fingerprint']; break;302 case 'content': x['content'] = await s3.getFileContent(vv); break;303 case 'contentAsBase64': x['contentAsBase64'] = Buffer.from(await s3.getFileContent(vv), 'utf-8').toString('base64'); break;304 case 'contentAsBase64Url': x['contentAsBase64Url'] = Buffer.from(await s3.getFileContent(vv), 'utf-8').toString('base64url'); break;305 case 'cdnUrl': x['cdnUrl'] = cdnObject ? await buildImageCdnUrl({...(cdnObject || {}), fingerprint: v['fingerprint']} as any, selection[k]) : undefined; break;306 case 'url': x['url'] = urlPattern ? buildUrlFromPattern(urlPattern, vars, v) : (await s3.getFileViewUrl(vv)).viewUrl; break;307 case 'urlInfos': x['urlInfos'] = await s3.getFileViewUrl(vv); break;308 case 'viewUrl': x['viewUrl'] = (await s3.getFileViewUrl(vv)).viewUrl; break;309 case 'viewUrlInfos': x['viewUrlInfos'] = await s3.getFileViewUrl(vv); break;310 case 'downloadUrl': x['downloadUrl'] = (await s3.getFileDownloadUrl(vv)).downloadUrl; break;311 case 'downloadUrlInfos': x['downloadUrlInfos'] = await s3.getFileDownloadUrl(vv); break;312 case 'uploadUrl': x['uploadUrl'] = (await s3.getFileUploadUrl(vv)).uploadUrl; break;313 case 'uploadUrlInfos': x['uploadUrlInfos'] = await s3.getFileUploadUrl(vv); break;314 case 'size':315 case 'realContentType':316 case 'eTag':317 case 'lastModified':318 const metadata = await s3.getFileMetadata(vv);319 switch (k) {320 case 'size': x['size'] = metadata.contentLength; break;321 case 'realContentType': x['realContentType'] = metadata.contentType; break;322 case 'eTag': x['eTag'] = metadata.eTag; break;323 case 'lastModified': x['lastModified'] = metadata.lastModified.getTime(); break;324 default: break;325 }326 break;327 default: break;328 }329 }));330 } else {331 await Promise.all(selected.map(async k => {332 switch (k) {333 case 'bucket': x['bucket'] = vv['bucket']; break;334 case 'key': x['key'] = vv['key']; break;335 case 'name': x['name'] = vv['name']; break;336 case 'uploadUrl': x['uploadUrl'] = (await s3.getFileUploadUrl(vv)).uploadUrl; break;337 case 'uploadUrlInfos': x['uploadUrlInfos'] = await s3.getFileUploadUrl(vv); break;338 default: break;339 }340 }));341 }342 return x;343}344function buildUrlFromPattern(pattern: string, vars: any, dynamicVars: any) {345 dynamicVars = {346 extension: computeExtensionFromContentType(dynamicVars['contentType']),347 ...dynamicVars,348 };349 pattern = replaceVars(pattern, vars);350 return replaceVars(pattern, dynamicVars, '\\<\\<', '\\>\\>');351}352const extensionMap = {353 'image/png': '.png',354 'image/jpeg': '.jpg',355 'image/svg+xml': '.svg',356 'image/x-icon': '.ico',357 'image/gif': '.gif',358 'image/ief': '.ief',359 'image/bmp': '.bmp',360 'image/tiff': '.tif',361 'application/octet-stream': '',362 'application/json': '.json',363 'text/javascript': '.js',364 'text/css': '.css',365 'text/csv': '.csv',366 'application/pdf': '.pdf',367 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': '.xlsx',368 'application/vnd.ms-excel': '.xls',369 'application/vnd.openxmlformats-officedocument.wordprocessingml.document': '.docx',370 'application/msword': '.doc',371 'application/vnd.openxmlformats-officedocument.presentationml.presentation': '.pptx',372 'application/vnd.ms-powerpoint': '.ppt',373 'application/rtf': '.rtf',374}375function computeExtensionFromContentType(type: string|undefined) {376 return extensionMap[type || ''] || '';377}378function buildPublicImageBucketKey(key) {379 const parts = key.split('', 10);380 parts[parts.length - 1] = parts[parts.length - 1].slice(0, 1);381 return `${parts.join('/')}/${key}`;382}383function buildPublicCssBucketKey(key) {384 const parts = key.split('', 10);385 parts[parts.length - 1] = parts[parts.length - 1].slice(0, 1);386 return `${parts.join('/')}/${key}`;387}388function buildPublicJsBucketKey(key) {389 const parts = key.split('', 10);390 parts[parts.length - 1] = parts[parts.length - 1].slice(0, 1);391 return `${parts.join('/')}/${key}`;392}393function buildPublicFileBucketKey(key) {394 const parts = key.split('', 10);395 parts[parts.length - 1] = parts[parts.length - 1].slice(0, 1);396 return `${parts.join('/')}/${key}`;397}398function buildImageCdnUrl({name = undefined, fingerprint}: {name?: string, fingerprint: string}, options = {} as {arguments?: any}) {399 if (!process.env.IMAGE_CDN_UP) return undefined;400 const params = {} as {qs?: string, color?: string, filter?: string[], flip?: string, format?: string, preset?: string[], quality?: string, radius?: string, rotation?: string, size?: string, theme?: string, trim?: string};401 let qs = '';402 options.arguments?.name && (name = options.arguments?.name);403 options.arguments?.qs && (qs = `${options.arguments?.qs}`);404 options.arguments?.color && (params.color = `${options.arguments?.color}`);405 options.arguments?.filter && (params.filter = options.arguments?.filter.split(/\*,\*/g).map(x => `${x}`));406 options.arguments?.flip && (params.flip = `${options.arguments?.flip}`);407 options.arguments?.format && (params.format = `${options.arguments?.format}`);408 options.arguments?.preset && (params.preset = options.arguments?.preset.split(/\*,\*/g).map(x => `${x}`));409 options.arguments?.quality && (params.quality = `${options.arguments?.quality}`);410 options.arguments?.radius && (params.radius = `${options.arguments?.radius}`);411 options.arguments?.rotation && (params.rotation = `${options.arguments?.rotation}`);412 options.arguments?.size && (params.size = `${options.arguments?.size}`);413 options.arguments?.theme && (params.theme = `${options.arguments?.theme}`);414 options.arguments?.trim && (params.trim = `${options.arguments?.trim}`);415 const u = process.env.IMAGE_CDN_UP416 .replace('{{fingerprint}}', fingerprint)417 .replace('{{name}}', name || '')418 .replace('{{path}}', `${fingerprint}/${name}`)419 ;420 if (!Object.keys(params).length && !qs) return u;421 const keys = Object.keys(params);422 keys.sort();423 let xx;424 const queryString = keys.reduce((acc, k) => {425 xx = buildQueryStringValuesParam(k, params[k]);426 if (!xx) return acc;427 acc = `${acc}${acc ? '&' : ''}${xx}`;428 return acc;429 }, qs);430 return `${u}?${queryString}`;431}432function buildQueryStringValuesParam(k, v) {433 if (Array.isArray(v)) {434 switch (v.length) {435 case 0: return undefined;436 case 1: return `${k}=${v[0]}`;437 default:438 return v.reduce((acc, vv) => {439 acc = `${acc}${acc ? '&' : ''}${k}[]${vv}`;440 return acc;441 }, '');442 }443 }444 if ((undefined === v) || ('' === v)) return undefined;445 return `${k}=${v}`;...

Full Screen

Full Screen

HttpClient.js

Source:HttpClient.js Github

copy

Full Screen

1let HttpClient = cc.Class({2 statics: {3 /** 最大超时重试次数 */4 MAX_TIMEOUT_TIMES: 3,5 /** 超时时间 */6 TIMEOUT: 5000,7 /**8 * 使用 Promise 异步处理;9 * 请求超时则会进行重试, 超时时间 10s, 重试次数 5;10 *11 * @param url 地址12 *13 * @returns {Promise<string>} 结果的promise对象14 */15 httpGet: function(url) {16 return new Promise((resolve, reject) => {17 try {18 HttpClient.httpGet0(url, resolve, reject, 0);19 } catch (e) {20 reject(url + " http get error:" + e.message);21 }22 });23 },24 httpGet0: function(url, resolve, reject, timeoutCount) {25 let xhr = cc.loader.getXMLHttpRequest();26 xhr.timeout = HttpClient.TIMEOUT;27 xhr.open("GET", url, true);28 if(cc.sys.isNative){29 xhr.setRequestHeader("Connection", "close");30 }31 xhr.ontimeout = function () {32 timeoutCount++;33 if (timeoutCount >= HttpClient.MAX_TIMEOUT_TIMES) {34 reject("http get request timeout");35 } else {36 HttpClient.httpGet0(url, resolve, reject, timeoutCount);37 }38 };39 xhr.onabort = function () {40 reject("http get request aborted");41 };42 xhr.onerror = function () {43 reject("http get request error");44 };45 xhr.onload = function () {46 if ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304) {47 resolve(xhr.responseText);48 } else {49 reject(url + " http get request error:" + xhr.status);50 }51 };52 xhr.send();53 },54 /**55 * 使用Promise方式发送 http/https post 请求;56 * 请求超时则会进行重试, 超时时间 10s, 重试次数 5;57 *58 * @param url 地址59 * @param msg 放在body里的数据60 * @param contentType 数据类型, 默认 'application/json'61 *62 * @returns {Promise<string>} 结果的 Promise 对象;63 */64 httpPost: function(url, msg, contentType) {65 return new Promise((resolve, reject) => {66 let realContentType = contentType;67 if (!contentType) {68 realContentType = "application/json";69 }70 try {71 HttpClient.httpPost0(url, msg, realContentType, resolve, reject, 0);72 } catch (e) {73 reject(url + " http post error:" + e.message);74 }75 });76 },77 httpPost0: function(url, msg, contentType, resolve, reject, timeoutCount) {78 let xhr = cc.loader.getXMLHttpRequest();79 xhr.timeout = HttpClient.TIMEOUT;80 xhr.open("POST", url, true);81 xhr.setRequestHeader("Content-Type", contentType);82 if(cc.sys.isNative){83 xhr.setRequestHeader("Connection", "close");84 }85 xhr.ontimeout = function () {86 timeoutCount++;87 if (timeoutCount >= HttpClient.MAX_TIMEOUT_TIMES) {88 reject("http post request timeout");89 } else {90 HttpClient.httpPost0(url, msg, contentType, resolve, reject, timeoutCount);91 }92 };93 xhr.onabort = function () {94 reject("http post request aborted");95 };96 xhr.onerror = function () {97 reject("http post request error");98 };99 xhr.onload = function () {100 if ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304) {101 resolve(xhr.responseText);102 } else {103 reject(url + " http post request error:" + xhr.status);104 }105 };106 xhr.send(msg);107 },108 /**109 * 使用Promise方式发送 http/https post 请求;110 * 请求超时则会进行重试, 超时时间 10s, 重试次数 5;111 *112 * @param url 地址113 * @param msg 放在body里的数据114 * @param contentType 数据类型, 默认 'application/json'115 *116 * @returns {Promise<string>} 结果的 Promise 对象;117 */118 httpPost: function(url, msg, contentType) {119 return new Promise((resolve, reject) => {120 let realContentType = contentType;121 if (!contentType) {122 realContentType = "application/json";123 }124 try {125 HttpClient.httpPost0(url, msg, realContentType, resolve, reject, 0);126 } catch (e) {127 reject(url + " http post error:" + e.message);128 }129 });130 },131 httpPost0: function(url, msg, contentType, resolve, reject, timeoutCount) {132 let xhr = cc.loader.getXMLHttpRequest();133 xhr.timeout = HttpClient.TIMEOUT;134 xhr.open("POST", url, true);135 xhr.setRequestHeader("Content-Type", contentType);136 if(cc.sys.isNative){137 xhr.setRequestHeader("Connection", "close");138 }139 xhr.ontimeout = function () {140 timeoutCount++;141 if (timeoutCount >= HttpClient.MAX_TIMEOUT_TIMES) {142 reject("http post request timeout");143 } else {144 HttpClient.httpPost0(url, msg, contentType, resolve, reject, timeoutCount);145 }146 };147 xhr.onabort = function () {148 reject("http post request aborted");149 };150 xhr.onerror = function () {151 reject("http post request error");152 };153 xhr.onload = function () {154 if ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304) {155 resolve(xhr.responseText);156 } else {157 reject(url + " http post request error:" + xhr.status);158 }159 };160 xhr.send(msg);161 }162 }...

Full Screen

Full Screen

assert.js

Source:assert.js Github

copy

Full Screen

1const Request = require('./request');2const Utils = require('./utils');3class Assert {4 static callbackWithAssertion(callback, assertion) {5 if (assertion.success) callback();6 callback(Utils.prettyPrintJson(assertion));7 }8 static getAssertionResult(success, expected, actual) {9 return {10 success,11 expected,12 actual,13 response: {14 statusCode: Request.getResponseObject().statusCode,15 headers: Request.getResponseObject().headers,16 body: Request.getResponseObject().body,17 },18 };19 }20 static assertResponseValue(valuePath, value) {21 const success = (valuePath === value);22 return this.getAssertionResult(success, valuePath, value);23 }24 static assertResponseCode(responseCode) {25 const realResponseCode = Request.getResponseObject().statusCode.toString();26 const success = (realResponseCode === responseCode);27 return this.getAssertionResult(success, responseCode, realResponseCode);28 }29 static assertResponseBodyContentType(contentType) {30 const realContentType = Utils.getContentType(Request.getResponseObject().body);31 const success = (realContentType === contentType);32 return this.getAssertionResult(success, contentType, realContentType);33 }34 static assertHeaderValue(header, expression) {35 const realHeaderValue = Request.getResponseObject().headers[header.toLowerCase()];36 const regex = new RegExp(expression);37 const success = (regex.test(realHeaderValue));38 return this.getAssertionResult(success, expression, realHeaderValue, this);39 }40 static assertResponseBodyContainsExpression(expression) {41 const regex = new RegExp(expression);42 const success = regex.test(Request.getResponseObject().body);43 return this.getAssertionResult(success, expression, null, this);44 }45 static assertPathInResponseBodyMatchesExpression(path, regexp) {46 const regExpObject = new RegExp(regexp);47 const evalValue = Utils.evaluatePath(path, Request.getResponseObject().body);48 const success = regExpObject.test(evalValue);49 return this.getAssertionResult(success, regexp, evalValue, this);50 }51}...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var apickli = require('apickli');2var apickliObject = new apickli.Apickli('https', 'httpbin.org');3apickliObject.realContentType('application/json');4console.log(apickliObject.realContentType());5var apickli = require('apickli');6var apickliObject = new apickli.Apickli('https', 'httpbin.org');7apickliObject.realContentType('application/json');8console.log(apickliObject.realContentType());9var apickli = require('apickli');10var apickliObject = new apickli.Apickli('https', 'httpbin.org');11apickliObject.realContentType('application/json');12console.log(apickliObject.realContentType());13var apickli = require('apickli');14var apickliObject = new apickli.Apickli('https', 'httpbin.org');15apickliObject.realContentType('application/json');16console.log(apickliObject.realContentType());17var apickli = require('apickli');18var apickliObject = new apickli.Apickli('https', 'httpbin.org');19apickliObject.realContentType('application/json');20console.log(apickliObject.realContentType());21var apickli = require('apickli');22var apickliObject = new apickli.Apickli('https', 'httpbin.org');23apickliObject.realContentType('application/json');24console.log(apickliObject.realContentType());25var apickli = require('apickli');26var apickliObject = new apickli.Apickli('https',

Full Screen

Using AI Code Generation

copy

Full Screen

1var apickli = require('apickli');2var apickliObject = new apickli.Apickli('http', 'httpbin.org');3apickliObject.realContentType('application/json');4var apickli = require('apickli-gherkin');5var apickliObject = new apickli.Apickli('http', 'httpbin.org');6apickliObject.realContentType('application/json');7var apickli = require('apickli-gherkin');8var apickliObject = new apickli.Apickli('http', 'httpbin.org');9apickliObject.realContentType('application/json');10var apickli = require('apickli-gherkin');11var apickliObject = new apickli.Apickli('http', 'httpbin.org');12apickliObject.realContentType('application/json');13var apickli = require('apickli-gherkin');14var apickliObject = new apickli.Apickli('http', 'httpbin.org');15apickliObject.realContentType('application/json');16var apickli = require('apickli-gherkin');17var apickliObject = new apickli.Apickli('http', 'httpbin.org');18apickliObject.realContentType('application/json');19var apickli = require('apickli-gherkin');20var apickliObject = new apickli.Apickli('http', 'httpbin.org');21apickliObject.realContentType('application/json');22var apickli = require('apickli-gherkin');23var apickliObject = new apickli.Apickli('http', 'httpbin.org');24apickliObject.realContentType('application/json');

Full Screen

Using AI Code Generation

copy

Full Screen

1var apickli = require('apickli');2var realContentType = apickli.realContentType;3var contentType = realContentType('application/json; charset=utf-8');4console.log(contentType);5"dependencies": {6 }7"dependencies": {8 }9Apickli is available on the Apigee Edge Public Maven Repository. To use Apickli, add the following to your package.json file: "dependencies": { "apickli": "1.0.0" }10Apickli is a Node.js module that provides functions for writing API tests with Cucumber. Apickli can be used with any testing framework that supports Cucumber. Apickli is a wrapper around the request module. It adds functions to make it easy to write API tests with Cucumber. Apickli is available on the Apigee Edge Public Maven Repository. To use Apickli, add the following to your package.json file: "dependencies": { "apickli": "1.0.0" }

Full Screen

Using AI Code Generation

copy

Full Screen

1const apickli = require('apickli');2When('I get the content type of response', function(callback) {3 this.realContentType = this.getResponseObject().headers['content-type'];4 callback();5});6Then('I see the content type as {string}', function(contentType, callback) {7 expect(this.realContentType).to.equal(contentType);8 callback();9});

Full Screen

Using AI Code Generation

copy

Full Screen

1var apickli = require('apickli');2var contentType = apickli.getRealContentType('application/json; charset=utf-8');3console.log(contentType);4var apickli = require('apickli');5var contentType = apickli.getRealContentType('application/json; charset=utf-8');6if (contentType == 'application/json') {7 console.log('Content type is application/json');8} else {9 console.log('Content type is not application/json');10}11var apickli = require('apickli');12var contentType = apickli.getRealContentType('application/json; charset=utf-8');13if (contentType == 'application/json') {14 console.log('Content type is application/json');15} else {16 console.log('Content type is not application/json');17}18var apickli = require('apickli');19var contentType = apickli.getRealContentType('application/json; charset=utf-8');20if (contentType == 'application/json') {21 console.log('Content type is application/json');22} else {23 console.log('Content type is not application/json');24}

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run apickli automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful