How to use the url.URLSearchParams function in url

To help you get started, we’ve selected a few url examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github graalvm / graaljs / test / parallel / test-whatwg-url-searchparams-constructor.js View on Github external
test(function() {
    var seed = new URLSearchParams('a=b&c=d');
    var params = new URLSearchParams(seed);
    assert_true(params != null, 'constructor returned non-null value.');
    assert_equals(params.get('a'), 'b');
    assert_equals(params.get('c'), 'd');
    assert_false(params.has('d'));
    // The name-value pairs are copied when created; later updates
    // should not be observable.
    seed.append('e', 'f');
    assert_false(params.has('e'));
    params.append('g', 'h');
    assert_false(seed.has('g'));
}, 'URLSearchParams constructor, object.');
github graalvm / graaljs / test / parallel / test-whatwg-url-searchparams-append.js View on Github external
test(function() {
    var params = new URLSearchParams();
    params.append('first', 1);
    params.append('second', 2);
    params.append('third', '');
    params.append('first', 10);
    assert_true(params.has('first'), 'Search params object has name "first"');
    assert_equals(params.get('first'), '1', 'Search params object has name "first" with value "1"');
    assert_equals(params.get('second'), '2', 'Search params object has name "second" with value "2"');
    assert_equals(params.get('third'), '', 'Search params object has name "third" with value ""');
    params.append('first', 10);
    assert_equals(params.get('first'), '1', 'Search params object has name "first" with value "1"');
}, 'Append multiple');
/* eslint-enable */
github DefinitelyTyped / DefinitelyTyped / types / node / v7 / node-tests.ts View on Github external
assert.deepEqual(values.next(), { value: "123", done: false});
        assert.deepEqual(values.next(), { value: "xyz", done: false});
        assert.deepEqual(values.next(), { value: undefined, done: true});

        searchParams.set('abc', 'b');
        assert.deepEqual(searchParams.getAll('abc'), ['b']);

        searchParams.delete('a');
        assert(!searchParams.has('a'));
        assert.equal(searchParams.get('a'), null);

        searchParams.sort();
    }

    {
        const searchParams = new url.URLSearchParams({
            user: 'abc',
            query: ['first', 'second']
        });

        assert.equal(searchParams.toString(), 'user=abc&query=first%2Csecond');
        assert.deepEqual(searchParams.getAll('query'), ['first,second']);
    }

    {
        // Using an array
        let params = new url.URLSearchParams([
            ['user', 'abc'],
            ['query', 'first'],
            ['query', 'second']
        ]);
        assert.equal(params.toString(), 'user=abc&query=first&query=second');
github rjgtav / tos-database / tos-patreon / src / index.js View on Github external
async function patreonAccessTokenRefresh() {
    let params = new url.URLSearchParams();
        params.append('grant_type', 'refresh_token');
        params.append('refresh_token', sharedVariables.PATREON_CREATOR_REFRESH_TOKEN);
        params.append('client_id', sharedVariables.PATREON_CLIENT_ID);
        params.append('client_secret', sharedVariables.PATREON_CLIENT_SECRET);

    let response = await fetch('https://www.patreon.com/api/oauth2/token', { method: 'POST', body: params });
        response = await response.json();

    if (response.error !== undefined)
        throw new Error('Failed to refresh Patreon AccessToken');

    let accessToken = response.access_token;
    let refreshToken = response.refresh_token;

    // As Patreon immediately destroys the current refresh token, we need to store the new one
    let variablesPath = path.join('..', 'variables.js');
github erezrokah / serverless-monorepo-app / services / api-service / e2e / utils / puppeteer.ts View on Github external
await page.click('button[type="submit"]');

  await page.waitForSelector('button[id="allow"]', {
    timeout: 5000,
    visible: true,
  });
  await page.click('button[id="allow"]');
  await page.waitForNavigation({ waitUntil: 'networkidle2' });

  const clientUrl = urls.filter(u => u.startsWith(redirectUri))[0];
  let token = '';
  if (clientUrl) {
    const hashQuery = clientUrl.substring(
      redirectUri.length + '/'.length + '#'.length,
    );
    const params = new URLSearchParams(hashQuery);
    token = params.get('id_token') || '';
    console.log('Login success, token:', token);
  } else {
    console.error('Login failed. Current url:', clientUrl);
  }

  await browser.close();
  return `Bearer ${token}`;
};
github danger / danger-js / source / platforms / bitbucket_cloud / BitBucketCloudAPI.ts View on Github external
private api = async (url: string, headers: any = {}, body: any = {}, method: string, suppressErrors?: boolean) => {
    if (this.credentials.type === "PASSWORD") {
      headers["Authorization"] = `Basic ${new Buffer(
        this.credentials.username + ":" + this.credentials.password
      ).toString("base64")}`
    } else {
      if (this.accessToken == null) {
        const params = new URLSearchParams()

        params.append("grant_type", "client_credentials")

        const authResponse = await this.performAPI(
          this.oauthURL,
          {
            ...headers,
            Authorization: `Basic ${new Buffer(this.credentials.oauthKey + ":" + this.credentials.oauthSecret).toString(
              "base64"
            )}`,
            "Content-Type": "application/x-www-form-urlencoded",
          },
          params,
          "POST",
          suppressErrors
        )
github itchio / itch / src / common / helpers / space.ts View on Github external
urlWithParams(newParams: { [key: string]: any }): string {
    const params = new URLSearchParams(this._query);
    for (const k of Object.keys(newParams)) {
      const v = newParams[k];
      if (v) {
        params.set(k, v);
      } else {
        params.delete(k);
      }
    }
    const queryString = params.toString();
    return format({
      protocol: this._protocol,
      hostname: this._hostname,
      pathname: this._pathname,
      slashes: true,
      search: queryString == "" ? null : `?${queryString}`,
    });
github nikityy / rutracker-api / lib / page-provider.js View on Github external
search(params) {
    if (!this.authorized) {
      return Promise.reject(new NotAuthorizedError());
    }

    const url = new URL(this.searchUrl);
    const body = new URLSearchParams();

    try {
      this.searchMiddlewares.forEach(middleware => {
        middleware(params, body, url);
      });
    } catch (err) {
      return Promise.reject(err);
    }

    return this.request({
      url: url.toString(),
      data: body.toString(),
      method: "POST",
      responseType: "arraybuffer",
      headers: {
        Cookie: this.cookie
github sourcefuse / loopback4-starter / src / modules / auth / login.controller.ts View on Github external
async googleCallback(
    @param.query.string('code') code: string,
    @param.query.string('state') state: string,
    @inject(RestBindings.Http.RESPONSE) response: Response,
  ): Promise {
    const clientId = new URLSearchParams(state).get('client_id');
    if (!clientId || !this.user) {
      throw new HttpErrors.Unauthorized(AuthErrorKeys.ClientInvalid);
    }
    const client = await this.authClientRepository.findOne({
      where: {
        clientId: clientId,
      },
    });
    if (!client || !client.redirectUrl) {
      throw new HttpErrors.Unauthorized(AuthErrorKeys.ClientInvalid);
    }
    try {
      const codePayload: ClientAuthCode = {
        clientId,
        user: this.user,
      };
github Ionaru / EVIE / server / src / routers / sso.router.ts View on Github external
private static async doAuthRequest(auth: string, code: string, refresh = false) {
        const requestOptions: AxiosRequestConfig = {
            headers: {
                'Authorization': 'Basic ' + auth,
                'Content-Type': 'application/x-www-form-urlencoded',
            },
        };

        const requestBody = refresh ?
            new URLSearchParams({grant_type: 'refresh_token', refresh_token: code}) :
            new URLSearchParams({grant_type: 'authorization_code', code});

        const authUrl = `${protocol}${oauthHost}${tokenPath}`;
        SSORouter.debug(`Requesting authorization: ${code} (refresh: ${refresh})`);
        return axiosInstance.post(authUrl, requestBody, requestOptions).catch((error: AxiosError) => {
            process.stderr.write(`Request failed: ${authUrl}\n${error.message}\n`);
            if (error.response) {
                process.stderr.write(`${JSON.stringify(error.response.data)}\n`);
            }
            Sentry.captureException(error);
            return;
        });
    }