本文整理汇总了TypeScript中@sindresorhus/is.object函数的典型用法代码示例。如果您正苦于以下问题:TypeScript object函数的具体用法?TypeScript object怎么用?TypeScript object使用的例子?那么, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了object函数的6个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。
示例1: async
const fetchFromAttachmentsIndex = async ({
name,
conversationId,
WhisperMessageCollection,
count,
}: {
name: 'hasVisualMediaAttachments' | 'hasFileAttachments';
conversationId: string;
WhisperMessageCollection: BackboneCollection<Message>;
count: number;
}): Promise<Array<Message>> => {
if (!is.string(conversationId)) {
throw new TypeError("'conversationId' is required");
}
if (!is.object(WhisperMessageCollection)) {
throw new TypeError("'WhisperMessageCollection' is required");
}
const collection = new WhisperMessageCollection();
const lowerReceivedAt = 0;
const upperReceivedAt = Number.MAX_VALUE;
const condition: IndexableBoolean = 1;
await deferredToPromise(
collection.fetch({
index: {
name,
lower: [conversationId, lowerReceivedAt, condition],
upper: [conversationId, upperReceivedAt, condition],
order: 'desc',
},
limit: count,
})
);
return collection.models.map(model => model.toJSON());
};
示例2:
export const createLastMessageUpdate = ({
currentLastMessageText,
currentTimestamp,
lastMessage,
lastMessageNotificationText,
}: {
currentLastMessageText: string | null;
currentTimestamp: number | null;
lastMessage: Message | null;
lastMessageNotificationText: string | null;
}): ConversationLastMessageUpdate => {
if (lastMessage === null) {
return {
lastMessage: '',
timestamp: null,
};
}
const { type } = lastMessage;
const isVerifiedChangeMessage = type === 'verified-change';
const isExpiringMessage = is.object(lastMessage.expirationTimerUpdate);
const shouldUpdateTimestamp = !isVerifiedChangeMessage && !isExpiringMessage;
const newTimestamp = shouldUpdateTimestamp
? lastMessage.sent_at
: currentTimestamp;
const shouldUpdateLastMessageText = !isVerifiedChangeMessage;
const newLastMessageText = shouldUpdateLastMessageText
? lastMessageNotificationText
: currentLastMessageText;
return {
lastMessage: newLastMessageText,
timestamp: newTimestamp,
};
};
示例3: setImmediate
setImmediate(async () => {
try {
for (const hook of options.hooks.beforeRequest) {
// eslint-disable-next-line no-await-in-loop
await hook(options);
}
// Serialize body
const {body, headers} = options;
const isForm = !is.nullOrUndefined(options.form);
const isJSON = !is.nullOrUndefined(options.json);
const isBody = !is.nullOrUndefined(body);
if ((isBody || isForm || isJSON) && withoutBody.has(options.method)) {
throw new TypeError(`The \`${options.method}\` method cannot be used with a body`);
}
if (isBody) {
if (isForm || isJSON) {
throw new TypeError('The `body` option cannot be used with the `json` option or `form` option');
}
if (is.object(body) && isFormData(body)) {
// Special case for https://github.com/form-data/form-data
headers['content-type'] = headers['content-type'] || `multipart/form-data; boundary=${body.getBoundary()}`;
} else if (!is.nodeStream(body) && !is.string(body) && !is.buffer(body)) {
throw new TypeError('The `body` option must be a stream.Readable, string, Buffer, Object or Array');
}
} else if (isForm) {
if (!is.object(options.form)) {
throw new TypeError('The `form` option must be an Object');
}
headers['content-type'] = headers['content-type'] || 'application/x-www-form-urlencoded';
options.body = (new URLSearchParams(options.form)).toString();
} else if (isJSON) {
headers['content-type'] = headers['content-type'] || 'application/json';
options.body = JSON.stringify(options.json);
}
// Convert buffer to stream to receive upload progress events (#322)
if (is.buffer(body)) {
options.body = toReadableStream(body);
uploadBodySize = body.length;
} else {
uploadBodySize = await getBodySize(options);
}
if (is.undefined(headers['content-length']) && is.undefined(headers['transfer-encoding'])) {
if ((uploadBodySize > 0 || options.method === 'PUT') && !is.undefined(uploadBodySize)) {
headers['content-length'] = uploadBodySize;
}
}
if (!options.stream && options.responseType === 'json' && is.undefined(headers.accept)) {
options.headers.accept = 'application/json';
}
requestUrl = options.href || (new URL(options.path, urlLib.format(options))).toString();
await get(options);
} catch (error) {
emitError(error);
}
});
示例4: default
export default (options, input?: TransformStream) => {
const emitter = new EventEmitter() as RequestAsEventEmitter;
const redirects = [] as string[];
let currentRequest: http.ClientRequest;
let requestUrl: string;
let redirectString: string;
let uploadBodySize: number | undefined;
let retryCount = 0;
let shouldAbort = false;
const setCookie = options.cookieJar ? util.promisify(options.cookieJar.setCookie.bind(options.cookieJar)) : null;
const getCookieString = options.cookieJar ? util.promisify(options.cookieJar.getCookieString.bind(options.cookieJar)) : null;
const agents = is.object(options.agent) ? options.agent : null;
const emitError = async (error: Error) => {
try {
for (const hook of options.hooks.beforeError) {
// eslint-disable-next-line no-await-in-loop
error = await hook(error);
}
emitter.emit('error', error);
} catch (error2) {
emitter.emit('error', error2);
}
};
const get = async (options: Options) => {
const currentUrl = redirectString || requestUrl;
if (options.protocol !== 'http:' && options.protocol !== 'https:') {
throw new UnsupportedProtocolError(options);
}
decodeURI(currentUrl);
let requestFn: RequestFunction;
if (is.function_(options.request)) {
requestFn = options.request;
} else {
requestFn = options.protocol === 'https:' ? https.request : http.request;
}
if (agents) {
const protocolName = options.protocol === 'https:' ? 'https' : 'http';
options.agent = agents[protocolName] || options.agent;
}
/* istanbul ignore next: electron.net is broken */
// No point in typing process.versions correctly, as
// process.version.electron is used only once, right here.
if (options.useElectronNet && (process.versions as any).electron) {
// @ts-ignore
const electron = dynamicRequire(module, 'electron') as any; // Trick webpack
requestFn = electron.net.request || electron.remote.net.request;
}
if (options.cookieJar) {
const cookieString = await getCookieString(currentUrl, {});
if (is.nonEmptyString(cookieString)) {
options.headers.cookie = cookieString;
}
}
let timings: Timings;
// TODO: Properly type this.
const handleResponse = async response => {
try {
/* istanbul ignore next: fixes https://github.com/electron/electron/blob/cbb460d47628a7a146adf4419ed48550a98b2923/lib/browser/api/net.js#L59-L65 */
if (options.useElectronNet) {
response = new Proxy(response, {
get: (target, name) => {
if (name === 'trailers' || name === 'rawTrailers') {
return [];
}
const value = target[name];
return is.function_(value) ? value.bind(target) : value;
}
});
}
const {statusCode} = response;
response.statusMessage = response.statusMessage || http.STATUS_CODES[statusCode];
response.url = currentUrl;
response.requestUrl = requestUrl;
response.retryCount = retryCount;
response.timings = timings;
response.redirectUrls = redirects;
response.request = {options};
response.isFromCache = response.fromCache || false;
delete response.fromCache;
const rawCookies = response.headers['set-cookie'];
if (options.cookieJar && rawCookies) {
await Promise.all(rawCookies.map(rawCookie => setCookie(rawCookie, response.url)));
}
if (options.followRedirect && 'location' in response.headers) {
//.........这里部分代码省略.........
示例5: lowercaseKeys
export const preNormalizeArguments = (options: any, defaults?: any) => {
if (is.nullOrUndefined(options.headers)) {
options.headers = {};
} else {
options.headers = lowercaseKeys(options.headers);
}
if (options.baseUrl && !options.baseUrl.toString().endsWith('/')) {
options.baseUrl += '/';
}
if (is.nullOrUndefined(options.hooks)) {
options.hooks = {};
} else if (!is.object(options.hooks)) {
throw new TypeError(`Parameter \`hooks\` must be an object, not ${is(options.hooks)}`);
}
for (const event of knownHookEvents) {
if (is.nullOrUndefined(options.hooks[event])) {
if (defaults) {
options.hooks[event] = [...defaults.hooks[event]];
} else {
options.hooks[event] = [];
}
}
}
if (is.number(options.timeout)) {
options.gotTimeout = {request: options.timeout};
} else if (is.object(options.timeout)) {
options.gotTimeout = options.timeout;
}
delete options.timeout;
const {retry} = options;
options.retry = {
retries: () => 0,
methods: new Set(),
statusCodes: new Set(),
errorCodes: new Set(),
maxRetryAfter: undefined
};
if (is.nonEmptyObject(defaults) && retry !== false) {
options.retry = {...defaults.retry};
}
if (retry !== false) {
if (is.number(retry)) {
options.retry.retries = retry;
} else {
options.retry = {...options.retry, ...retry};
}
}
if (!options.retry.maxRetryAfter && options.gotTimeout) {
options.retry.maxRetryAfter = Math.min(...[options.gotTimeout.request, options.gotTimeout.connection].filter(n => !is.nullOrUndefined(n)));
}
if (is.array(options.retry.methods)) {
options.retry.methods = new Set(options.retry.methods.map(method => method.toUpperCase()));
}
if (is.array(options.retry.statusCodes)) {
options.retry.statusCodes = new Set(options.retry.statusCodes);
}
if (is.array(options.retry.errorCodes)) {
options.retry.errorCodes = new Set(options.retry.errorCodes);
}
if (options.dnsCache) {
const cacheableLookup = new CacheableLookup({cacheAdapter: options.dnsCache});
options.lookup = cacheableLookup.lookup;
delete options.dnsCache;
}
return options;
};
示例6: merge
export const normalizeArguments = (url, options, defaults?: any) => {
if (is.plainObject(url)) {
options = {...url, ...options};
url = options.url || '';
delete options.url;
}
if (defaults) {
options = merge({}, defaults.options, options ? preNormalizeArguments(options, defaults.options) : {});
} else {
options = merge({}, preNormalizeArguments(options));
}
if (!is.string(url) && !is.object(url)) {
throw new TypeError(`Parameter \`url\` must be a string or object, not ${is(url)}`);
}
if (is.string(url) && !(url === '' && !options.baseUrl)) {
if (options.baseUrl) {
if (url.startsWith('/')) {
url = url.slice(1);
}
} else {
url = url.replace(/^unix:/, 'http://$&');
}
url = urlToOptions(new URL(url, options.baseUrl));
} else if (is(url) === 'URL') {
url = urlToOptions(url);
}
// Override both null/undefined with default protocol
options = merge({path: ''}, url, {protocol: url.protocol || 'https:'}, options);
for (const hook of options.hooks.init) {
const called = hook(options);
if (is.promise(called)) {
throw new TypeError('The `init` hook must be a synchronous function');
}
}
const {baseUrl} = options;
Object.defineProperty(options, 'baseUrl', {
set: () => {
throw new Error('Failed to set baseUrl. Options are normalized already.');
},
get: () => baseUrl
});
let {searchParams} = options;
delete options.searchParams;
if (options.query) {
if (!shownDeprecation) {
console.warn('`options.query` is deprecated. We support it solely for compatibility - it will be removed in Got 11. Use `options.searchParams` instead.');
shownDeprecation = true;
}
searchParams = options.query;
delete options.query;
}
// TODO: This should be used in the `options` type instead
interface SearchParams {
[key: string]: string | number | boolean | null;
}
if (is.nonEmptyString(searchParams) || is.nonEmptyObject(searchParams) || searchParams instanceof URLSearchParams) {
if (!is.string(searchParams)) {
if (!(searchParams instanceof URLSearchParams)) {
validateSearchParams(searchParams);
searchParams = searchParams as SearchParams;
}
searchParams = (new URLSearchParams(searchParams)).toString();
}
options.path = `${options.path.split('?')[0]}?${searchParams}`;
}
if (options.hostname === 'unix') {
const matches = /(.+?):(.+)/.exec(options.path);
if (matches) {
const [, socketPath, path] = matches;
options = {
...options,
socketPath,
path,
host: null
};
}
}
const {headers} = options;
for (const [key, value] of Object.entries(headers)) {
if (is.nullOrUndefined(value)) {
delete headers[key];
}
//.........这里部分代码省略.........