本文整理汇总了TypeScript中querystring.parse函数的典型用法代码示例。如果您正苦于以下问题:TypeScript parse函数的具体用法?TypeScript parse怎么用?TypeScript parse使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了parse函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。
示例1: Promise
const promise: Promise<SUSHInfo> = new Promise((resolve, reject) => {
const sheetUrlObj = new URL(sheetUrl);
// Parse URL
const sheetId = (sheetUrl.match(sheetIdRegExp) || [])[1];
if (!sheetId) {
throw new Error('sheetUrl is invalid.');
}
// Get gid from hash
const hashQuery = Object.assign(
qs.parse(sheetUrlObj.hash.substr(1)),
qs.parse(sheetUrlObj.search.substr(1))
);
if (!('gid' in hashQuery)) {
throw new Error('sheetUrl must contain gid.');
}
// Convert gid to wid
const sheetKey = Util.convertGidToWid(hashQuery.gid);
const sheetDataUrl =
`https://spreadsheets.google.com/feeds/list/${sheetId}/${sheetKey}/public/values?alt=json`;
// Fetch Google Spreadsheet
const xhr = new XMLHttpRequest();
xhr.open('GET', sheetDataUrl, true);
xhr.addEventListener('load', () => resolve(xhr));
xhr.addEventListener('error', (ev) => reject(ev.error));
xhr.send();
})
示例2: getAddressDetails
/**
* Process address into address and memo id
*
* @param address {String} the address
* @returns {Object} object containing address and memo id
*/
getAddressDetails(address) {
const destinationDetails = url.parse(address);
const queryDetails = querystring.parse(destinationDetails.query);
const destinationAddress = destinationDetails.pathname;
if (!stellar.StrKey.isValidEd25519PublicKey(destinationAddress)) {
throw new Error(`invalid address: ${address}`);
}
// address doesn't have a memo id
if (destinationDetails.pathname === address) {
return {
address: address,
memoId: null
};
}
if (!queryDetails.memoId) {
// if there are more properties, the query details need to contain the memo id property
throw new Error(`invalid address: ${address}`);
}
try {
new BigNumber(queryDetails.memoId);
} catch (e) {
throw new Error(`invalid address: ${address}`);
}
if (!this.isValidMemoId(queryDetails.memoId)) {
throw new Error(`invalid address: ${address}`);
}
return {
address: destinationAddress,
memoId: queryDetails.memoId
};
}
示例3: ParseTorrent
const tabUpdated = (tabId: number, url: string, state: TorrentsState) => {
const { torrentStateMap, torrentObjMap } = state
const origTorrentState: TorrentState = torrentStateMap[tabId]
const origInfoHash = origTorrentState ? origTorrentState.infoHash : undefined
let newTorrentState: TorrentState | undefined
let newInfoHash: string | undefined
// create new torrent state
const parsedURL = new window.URL(url)
const torrentId = parsedURL.href
if (parsedURL.protocol === 'magnet:') { // parse torrent
try {
const { name, infoHash, ix } = ParseTorrent(torrentId)
newInfoHash = infoHash
newTorrentState = { tabId, torrentId, name, infoHash, ix }
} catch (error) {
newTorrentState = { tabId, torrentId, errorMsg: error.message }
}
} else if (parsedURL.protocol === 'https:' || parsedURL.protocol === 'http:') {
const name = parsedURL.pathname.substr(parsedURL.pathname.lastIndexOf('/') + 1)
// for .torrent case, ix (index of file) for selecting a specific file in
// the file list is given in url like #ix=5
let ix: number | undefined = Number(parse(parsedURL.hash.slice(1)).ix)
ix = Number.isNaN(ix) ? undefined : ix
// Use an existing infoHash if it's the same torrentId
const torrentUrl = parsedURL.origin + parsedURL.pathname
const key = Object.keys(torrentStateMap).find(
key => torrentStateMap[key].infoHash &&
torrentStateMap[key].torrentId === torrentUrl)
newInfoHash = key
? torrentStateMap[key].infoHash
: undefined
newTorrentState = { tabId, torrentId, name, ix, infoHash: newInfoHash }
}
// delete old torrent state
delete torrentStateMap[tabId]
// unsubscribe old torrent if not the same
const isSameTorrent = newInfoHash && origInfoHash === newInfoHash
if (origInfoHash && torrentObjMap[origInfoHash] && !isSameTorrent) {
torrentObjMap[origInfoHash].tabClients.delete(tabId)
if (!torrentObjMap[origInfoHash].tabClients.size) {
delete torrentObjMap[origInfoHash]
delTorrent(origInfoHash)
}
}
// save new torrent state and subscribe directly if torrent already existed
if (newTorrentState) {
torrentStateMap[tabId] = newTorrentState
if (newInfoHash && torrentObjMap[newInfoHash]) {
torrentObjMap[newInfoHash].tabClients.add(tabId)
}
}
return { ...state, torrentStateMap, torrentObjMap }
}
示例4: http_assemble_json
function http_assemble_json(bodyParts, cb) {
let body = Buffer.concat(bodyParts).toString()
if (body.length > 0) {
try {
let data = JSON.parse(body)
cb(data)
} catch (e) {
if (e instanceof SyntaxError) {
let qbody = querystring.parse(body)
if(qbody) {
cb(qbody)
} else {
console.log('payload not understood', JSON.stringify(body.substr(0, 280)))
cb()
}
} else {
console.log('aborting connection.', e.name)
cb()
}
}
} else {
console.log('empty body. closed.')
cb()
}
}
示例5: parseResponse
/**
* Parse the response automatically.
*/
function parseResponse (response: Response) {
const body = response.body
if (typeof body !== 'string') {
return
}
if (body === '') {
response.body = null
return
}
const type = response.type()
try {
if (JSON_MIME_REGEXP.test(type)) {
response.body = body === '' ? null : JSON.parse(body)
} else if (QUERY_MIME_REGEXP.test(type)) {
response.body = parseQuery(body)
}
} catch (err) {
return Promise.reject(response.error('Unable to parse response body: ' + err.message, 'EPARSE', err))
}
}
示例6: setTimeout
echoServer.use(function(req: IncomingMessage, res: ServerResponse) {
let urlParts = req.url.split("?");
let returnResponse = () => {
res.setHeader('Content-Type', 'text/plain');
res.writeHead(200);
req.pipe(res);
};
if (urlParts.length > 1) {
const parameters = querystring.parse(urlParts[1]);
if (parameters.d) {
res.setHeader('d', parameters.d);
}
if (parameters.t) {
res.setHeader('t', parameters.t);
setTimeout(returnResponse, parameters.t)
}
else {
returnResponse();
}
return;
}
returnResponse();
});
示例7: reject
(err, res, body) => {
if (err) {
console.log('POST code error: ' + err.message);
reject(err);
return;
}
if (res.statusCode !== 200) {
console.log('POST code error: ' + res.statusCode);
reject(new Error('Invalid response: ' + res.statusCode));
return;
}
const parsed = querystring.parse(body);
if (!parsed.access_token) {
console.log('Body parsing error: ' + body);
reject(new Error('Invalid body: ' + body));
}
console.log('Login: Success!');
fs.writeFile(this.tokens_path, JSON.stringify({github: parsed.access_token}), {encoding: 'utf8'});
resolve(parsed.access_token);
}
示例8: constructor
constructor(tab: string, instanceIn: TabInstance) {
this.tab = tab;
let instance = instanceIn || eo;
this._instance = instance;
this._page = currentPage(instance) || eo;
const { resource, url } = this._page;
if (resource) {
const slashIndex = resource.indexOf("/");
if (slashIndex > 0) {
this.prefix = resource.substring(0, slashIndex);
this.suffix = resource.substring(slashIndex + 1);
} else {
this.prefix = resource;
}
}
if (url) {
try {
const parsed = nodeURL.parse(url);
this._protocol = parsed.protocol;
this._hostname = parsed.hostname;
this._pathname = parsed.pathname;
this._query = querystring.parse(parsed.query);
if (parsed.pathname) {
this._pathElements = parsed.pathname.replace(/^\//, "").split("/");
}
} catch (e) {
// TODO: figure this out
console.log(`Could not parse url: `, e);
}
}
}
示例9: _parseQuery
/**
* Parses the template query string
* @param text The query string to parse
* @hidden
*/
private _parseQuery(text: string): void {
var query = parseQueryString(text);
this._queryParams = new Map();
var seen = new Set<string>();
for(let name in query) {
if(query[name] !== undefined) {
var value = query[name];
var error: string;
if(!value) {
error = "Missing value";
}
else if(value.length < 3 || value[0] != "{" || value[value.length-1] != "}") {
error = "Value must be a parameter name in the format '{name}'";
}
else {
var param = value.substring(1, value.length - 1);
if ((this._pathParams && this._pathParams.indexOf(param) != -1) || seen.has(param)) {
error = `Duplicate parameter name '${param}'`;
}
}
if(error) {
throw new Error(`Invalid query '${name}': ${error}.`);
}
// save the map between the query param and the operation param, trimming off the leading colon
this._queryParams.set(name, param);
seen.add(param);
}
}
}
示例10: navigate
export function navigate(url: string) {
try {
const parsed = URL.parse(url);
if (parsed.protocol === "emulator:") {
const params = QueryString.parse(parsed.query);
if (parsed.host === 'inspect') {
navigateInspectUrl(params);
} else if (parsed.host === 'appsettings') {
navigateAppSettingsUrl(params);
} else if (parsed.host === 'botcreds') {
navigateBotCredsUrl(params);
} else if (parsed.host === 'command') {
navigateCommandUrl(params);
}
} else if (parsed.protocol.startsWith(PaymentEncoder.PaymentEmulatorUrlProtocol)) {
navigatePaymentUrl(parsed.path);
} else if (parsed.protocol.startsWith(OAuthClientEncoder.OAuthEmulatorUrlProtocol)) {
navigateEmulatedOAuthUrl(url.substring(8));
} else if (parsed.protocol.startsWith(OAuthLinkEncoder.OAuthUrlProtocol)) {
navigateOAuthUrl(url.substring(12));
} else if (parsed.protocol.startsWith('file:')) {
// ignore
} else if (parsed.protocol.startsWith('javascript:')) {
// ignore
} else {
shell.openExternal(url, { activate: true });
}
} catch (e) {
log.error(e.message);
}
}
示例11: handleApiAsync
function handleApiAsync(req: http.IncomingMessage, res: http.ServerResponse, elts: string[]): Promise<any> {
let opts: U.Map<string> = querystring.parse(url.parse(req.url).query)
let innerPath = elts.slice(2).join("/").replace(/^\//, "")
let filename = path.resolve(path.join(fileDir, innerPath))
let meth = req.method.toUpperCase()
let cmd = meth + " " + elts[1]
let readJsonAsync = () =>
nodeutil.readResAsync(req)
.then(buf => JSON.parse(buf.toString("utf8")))
if (cmd == "GET list")
return returnDirAsync(innerPath, 3)
.then<ks.FsPkgs>(lst => {
return {
pkgs: lst
}
})
else if (cmd == "GET stat")
return statOptAsync(filename)
.then(st => {
if (!st) return {}
else return {
mtime: st.mtime.getTime()
}
})
else if (cmd == "GET pkg")
return readPkgAsync(innerPath, true)
else if (cmd == "POST pkg")
return readJsonAsync()
.then(d => writePkgAsync(innerPath, d))
else throw throwError(400)
}
示例12: verifyUrl
verifyUrl(req: Request, addressReader?: Types.AddressReader): Types.VerifyResult {
const url = req.protocol+'://'+req.get('host')+req.url;
if( url.length < 33 || !this.verifyString( url.substring(0, url.length-32), url.substr(-32) ) ) {
return Types.VerifyResult.blackholed;
}
// get signed data
let lastAmpPos = url.lastIndexOf('&signed=');
if(lastAmpPos == -1) {
lastAmpPos = url.lastIndexOf('?signed=');
}
if(lastAmpPos == -1) {
return Types.VerifyResult.blackholed;
}
const data = querystring.parse( url.substring(lastAmpPos+8, url.length-33), ';', ':');
req.url = url.substr(0, lastAmpPos);
// check additional conditions
if(data.a && addressReader && data.a != addressReader(req)) {
return Types.VerifyResult.blackholed;
}
if(data.m && data.m.indexOf(req.method) == -1) {
return Types.VerifyResult.blackholed;
}
if(data.e && data.e < Math.ceil(+new Date()/1000)) {
return Types.VerifyResult.expired;
}
return Types.VerifyResult.ok;
}
示例13:
responses.forEach(response => {
let urlParts = response.request.path.split("?");
const parameters = querystring.parse(urlParts[1]);
if (parameters.d != response.data) {
throw `Expected '${parameters.d}' but received '${response.data}'`;
}
});
示例14: doAsync
doAsync(async () => {
const queryParams = querystring.parse(parsedURL.query);
const gameId = parseInt(queryParams["game_id"] as string, 10);
const uploadId = parseInt(queryParams["upload_id"] as string, 10);
logger.info(`Should queue install because of URL: ${url}`);
const { game } = await mcall(messages.FetchGame, { gameId });
await queueInstall(store, game, uploadId);
});
示例15: function
http.createServer(function (req, resultServer) {
if (req.url.match(/^\/login/)) {
var param = qs.parse(req.url.split('?')[1]);
remote.auth(param.user, param.pass, function (error, resultAuth) {
resultServer.end(error ? error : resultAuth);
});
}
}).listen(process.argv[2]);