querystring#stringify TypeScript Examples

The following examples show how to use querystring#stringify. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: bookmarkPostMutation.ts    From lexicon with MIT License 6 votes vote down vote up
bookmarkPostResolver: FieldResolver<
  'Mutation',
  'bookmarkPost'
> = async (_, { postId }, context: Context) => {
  const config = {
    headers: {
      'Content-Type': CONTENT_FORM_URLENCODED,
    },
  };
  let body = snakecaseKeys({ postId });
  try {
    let { data } = await context.client.post(
      `/bookmarks.json`,
      stringify(body),
      config,
    );
    return data;
  } catch (e) {
    errorHandler(e);
  }
}
Example #2
Source File: AvatarDropdown.tsx    From anew-server with MIT License 6 votes vote down vote up
loginOut = async () => {
  await AuthLogout();
  localStorage.removeItem('token');
  localStorage.removeItem('expires');
  const { query = {}, pathname } = history.location;
  const { redirect } = query;
  // Note: There may be security issues, please note
  if (window.location.pathname !== '/user/login' && !redirect) {
    history.replace({
      pathname: '/user/login',
      search: stringify({
        redirect: pathname,
      }),
    });
  }
}
Example #3
Source File: AvatarDropdown.tsx    From ant-design-pro-V5-multitab with MIT License 6 votes vote down vote up
loginOut = async () => {
  await outLogin();
  const { query, pathname } = history.location;
  const { redirect } = query;
  // Note: There may be security issues, please note
  if (window.location.pathname !== '/user/login' && !redirect) {
    history.replace({
      pathname: '/user/login',
      search: stringify({
        redirect: pathname,
      }),
    });
  }
}
Example #4
Source File: request.ts    From sidebar with Apache License 2.0 6 votes vote down vote up
bizCodeHandler = async (response: Response): Promise<Response> => {
  // 非json响应直接返回,不判断业务状态码,也没有业务状态码
  if (
    !response.headers.has('content-type') ||
    !response.headers.get('content-type')?.includes('application/json')
  ) {
    return response;
  }

  const data = await response.clone().json();
  if (data && data.code !== 0) {

    if (codeMessage[data.code]) {
      message.error(codeMessage[data.code]);
    }

    if (data && data.code === 10000887) {
      const queryString = stringify({
        redirect: window.location.href,
      });

      if (!window.location.href.includes("/staff-frontend/login")) { // 避免登录页的请求会话失效时,重复跳转
        history.push(`/staff-frontend/login?${queryString}`);
      }

      return response;
    }
  }

  return response;
}
Example #5
Source File: StaffFrontendSecurityLayout.tsx    From sidebar with Apache License 2.0 6 votes vote down vote up
render() {
    const {isReady} = this.state;
    const {children, loading} = this.props;
    // You can replace it to your authentication rule (such as check token exists)
    // You can replace it with your own login authentication rules (such as judging whether the token exists)
    const isLogin = localStorage.getItem(LSExtStaffID) !== null;
    const queryString = stringify({
      redirect: window.location.href,
    });

    if ((!isLogin && loading) || !isReady) {
      return <PageLoading/>;
    }

    if (!isLogin && window.location.pathname !== '/staff-frontend/login') {
      return <Redirect to={`/staff-frontend/login?${queryString}`}/>;
    }
    return children;
  }
Example #6
Source File: StaffAdminSecurityLayout.tsx    From dashboard with Apache License 2.0 6 votes vote down vote up
render() {
    const {isReady} = this.state;
    const {children, loading} = this.props;
    // You can replace it to your authentication rule (such as check token exists)
    // You can replace it with your own login authentication rules (such as judging whether the token exists)
    const isLogin = localStorage.getItem(LSExtStaffAdminID) !== null;
    const queryString = stringify({
      redirect: window.location.href,
    });

    if ((!isLogin && loading) || !isReady) {
      return <PageLoading/>;
    }
    if (!isLogin && window.location.pathname !== '/staff-admin/login') {
      return <Redirect to={`/staff-admin/login?${queryString}`}/>;
    }
    return children;
  }
Example #7
Source File: smoketest.ts    From office-booker with MIT License 6 votes vote down vote up
authRoutes = [
  ['GET', `/api/offices`],
  ['GET', `/api/offices/an-office`],
  ['GET', `/api/users`],
  ['GET', `/api/users/${args.user}`],
  ['PUT', `/api/users/${args.user}`],
  ['GET', `/api/bookings`],
  ['GET', `/api/bookings?${stringify({ user: args.user })}`],
  ['POST', `/api/bookings`],
  ['DELETE', `/api/bookings/123`],
  ['POST', `api/selftest`],
]
Example #8
Source File: spotify.ts    From natemoo-re with MIT License 6 votes vote down vote up
async function getAuthorizationToken() {
  const url = new URL("https://accounts.spotify.com/api/token");
  const body = stringify({
    grant_type: "refresh_token",
    refresh_token,
  });
  const response = await fetch(`${url}`, {
    method: "POST",
    headers: {
      Authorization,
      "Content-Type": "application/x-www-form-urlencoded",
    },
    body,
  }).then((r) => r.json());

  return `Bearer ${response.access_token}`;
}
Example #9
Source File: changeUsernameMutation.ts    From lexicon with MIT License 6 votes vote down vote up
changeUsernameResolver: FieldResolver<
  'Mutation',
  'changeUsername'
> = async (_, { newUsername, oldUsername }, context: Context) => {
  const config = {
    headers: {
      'Content-Type': CONTENT_FORM_URLENCODED,
    },
  };
  let body = snakecaseKeys({ newUsername });
  try {
    let { data } = await context.client.put(
      `/u/${oldUsername}/preferences/username.json`,
      stringify(body),
      config,
    );
    return data;
  } catch (e) {
    errorHandler(e);
  }
}
Example #10
Source File: newPrivateMessageMutation.ts    From lexicon with MIT License 6 votes vote down vote up
newPrivateMessageResolver: FieldResolver<
  'Mutation',
  'newPrivateMessage'
> = async (_, { newPrivateMessageInput }, context: Context) => {
  let pmInputSnake = snakecaseKey({
    ...newPrivateMessageInput,
    targetRecipients: newPrivateMessageInput.targetRecipients.join(','),
    archetype: 'private_message',
  });
  const config = {
    headers: {
      'Content-Type': CONTENT_FORM_URLENCODED,
    },
  };
  try {
    let { data } = await context.client.post(
      '/posts.json',
      stringify(pmInputSnake),
      config,
    );
    return camelcaseKey(data, { deep: true });
  } catch (e) {
    errorHandler(e);
  }
}
Example #11
Source File: flagPostMutation.ts    From lexicon with MIT License 6 votes vote down vote up
flagPostResolver: FieldResolver<'Mutation', 'flagPost'> = async (
  _,
  { postId, postActionTypeId },
  context: Context,
) => {
  const config = {
    headers: {
      'Content-Type': CONTENT_FORM_URLENCODED,
    },
  };
  let body = {
    id: postId,
    // eslint-disable-next-line @typescript-eslint/camelcase
    post_action_type_id: postActionTypeId,
  };
  try {
    let { data } = await context.client.post(
      `/post_actions.json`,
      stringify(body),
      config,
    );
    return camelcaseKeys(data, { deep: true });
  } catch (e) {
    errorHandler(e);
  }
}
Example #12
Source File: addEmailMutation.ts    From lexicon with MIT License 6 votes vote down vote up
addEmailMutation: FieldResolver<'Mutation', 'addEmail'> = async (
  _,
  { email, username },
  context: Context,
) => {
  let body = {
    email,
  };
  const config = {
    headers: {
      'Content-Type': CONTENT_FORM_URLENCODED,
    },
  };
  try {
    await context.client.post(
      `/u/${username}/preferences/email.json`,
      stringify(body),
      config,
    );
    return 'success';
  } catch (e) {
    throw errorHandler(e);
  }
}
Example #13
Source File: registerMutation.ts    From lexicon with MIT License 6 votes vote down vote up
registerMutationResolver: FieldResolver<
  'Mutation',
  'register'
> = async (_, { registerInput }, __) => {
  try {
    let csrfSession = await getCsrfSession();
    let { cookies, ...hpChallenge } = await getHpChallenge(csrfSession);
    const config = {
      headers: {
        withCredentials: true,
        Cookie: cookies,
        'x-csrf-token': csrfSession.csrf,
        'Content-Type': CONTENT_FORM_URLENCODED,
      },
    };
    let snakecaseBody = snakecaseKeys({ ...registerInput, ...hpChallenge });
    let { data } = await discourseClient.post(
      '/users.json',
      stringify(snakecaseBody),
      config,
    );

    if (data.user_id) {
      return camelcaseKeys(data, { deep: true });
    }
    return { success: false, message: `Registration is  unavailable.` };
  } catch (error) {
    errorHandler(error);
  }
}
Example #14
Source File: SecurityLayout.tsx    From ui-visualization with MIT License 6 votes vote down vote up
render() {
    const { isReady } = this.state;
    const { children, loading, currentUser } = this.props;
    // You can replace it to your authentication rule (such as check token exists)
    // 你可以把它替换成你自己的登录认证规则(比如判断 token 是否存在)
    const isLogin = currentUser && currentUser.userid;
    const queryString = stringify({
      redirect: window.location.href,
    });

    if ((!isLogin && loading) || !isReady) {
      return <PageLoading />;
    }
    if (!isLogin && window.location.pathname !== '/user/login') {
      return <Redirect to={`/user/login?${queryString}`} />;
    }
    return children;
  }
Example #15
Source File: queue.ts    From workers-queue with MIT License 6 votes vote down vote up
async function createConfig(): Promise<Response> {
    const config = await pullConfig();
    let messages = await pullMessages();

    if (!messages) {
        messages = [];
    }

    if (messages.length === 0) {
        if (config.queue.saleComplete) {
            messages.push('THE SALE IS NOW COMPLETE, THANK YOU FOR PARTICIPATING');
        } else {
            if (config.queue.saleStart === -1 || config.queue.saleStart > currentTime()) {
                messages.push('THE SALE IS STARTING SOON');
            } else {
                messages.push('THE SALE HAS NOW STARTED');
            }
        }
    }

    const publicConfig: PublicConfig = {
        enabled: config.session.enabled,
        pollInterval: config.queue.pollInterval,
        siteKey: config.captcha.siteKey,
        messages,
    };

    return new Response(JSON.stringify(publicConfig), {
        headers: {
            'Cache-Control': 'max-age=15',
            'Content-Type': 'application/json',
        },
    });
}
Example #16
Source File: queue.ts    From workers-queue with MIT License 6 votes vote down vote up
async function verifyCaptcha(
    request: Request,
    config: Config,
    token: string,
    pollTime: Date,
): Promise<[boolean, Poll]> {
    const response = await fetch('https://www.google.com/recaptcha/api/siteverify', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: stringify({
            secret: config.captcha.secretKey,
            response: token,
            remoteip: request.headers.get(CLIENT_IP_HEADER),
        }),
    });

    switch (response.status) {
        case 200:
            const captcha: CaptchaResponse = await response.json();
            return [
                captcha.success && captcha.score >= 0.7 && captcha.action === config.captcha.action,
                { timestamp: pollTime.toISOString(), captcha },
            ];
    }

    return [false, { timestamp: new Date().toISOString() }];
}
Example #17
Source File: SecurityLayout.tsx    From ant-design-pro-V4 with MIT License 6 votes vote down vote up
render() {
    const { isReady } = this.state;
    const { children, loading, currentUser } = this.props;
    // You can replace it to your authentication rule (such as check token exists)
    // You can replace it with your own login authentication rules (such as judging whether the token exists)
    const isLogin = currentUser && currentUser.userid;
    const queryString = stringify({
      redirect: window.location.href,
    });

    if ((!isLogin && loading) || !isReady) {
      return <PageLoading />;
    }
    if (!isLogin && window.location.pathname !== '/user/login') {
      return <Redirect to={`/user/login?${queryString}`} />;
    }
    return children;
  }
Example #18
Source File: queue.ts    From workers-queue with MIT License 6 votes vote down vote up
async function QueueResponse(
    request: Request,
    config: Config,
    session: Session,
    status: Status,
    redirectUrl?: string,
): Promise<Response> {
    const pollResponse: PollResponse = { status, redirectUrl };
    const [signedSession, sessionExpiry] = await updateSession(request, config, session);

    const response = new Response(JSON.stringify(pollResponse), {
        headers: {
            'Content-Type': 'application/json',
        },
    });

    setCookie(response, config.session.cookieName, signedSession, sessionExpiry);

    return response;
}
Example #19
Source File: paramsSerializer.ts    From linkedin-private-api with MIT License 6 votes vote down vote up
paramsSerializer = (params: Record<string, string | Record<string, string>>): string => {
  const encodedParams = mapValues(params, value => {
    if (!isArray(value) && !isPlainObject(value)) {
      return value.toString();
    }

    if (isArray(value)) {
      return `List(${value.join(',')})`;
    }

    const encodedList = reduce(
      value as Record<string, string>,
      (res, filterVal, filterKey) => `${res}${res ? ',' : ''}${encodeFilter(filterVal, filterKey)}`,
      '',
    );

    return `List(${encodedList})`;
  });

  return stringify(encodedParams, undefined, undefined, {
    encodeURIComponent: uri => uri,
  });
}
Example #20
Source File: uri-utils.ts    From commercetools-sdk-typescript with MIT License 6 votes vote down vote up
function formatQueryString(variableMap: VariableMap) {
  const map = cleanObject(variableMap)
  const result = stringify(map)
  if (result === '') {
    return ''
  }
  return `?${result}`
}
Example #21
Source File: login.view.tsx    From malagu with MIT License 6 votes vote down vote up
export function Login() {
    const location = useLocation();
    const size = useContext(ResponsiveContext);
    const intl = useIntl();
    const targetUrlParameter = ConfigUtil.get<string>('malagu.security.targetUrlParameter');
    const registrations = ConfigUtil.get<{[key: string]: { icon?: string, clientName: string } }>('malagu.oauth2.client.registrations');
    const redirect = parse(location.search && location.search.substring(1))[targetUrlParameter];
    const queryStr = redirect ? `?${stringify({ [targetUrlParameter]: redirect})}` : '';
    return (
    <StyledWraper style={size === 'small' ? { top: 0, bottom: 0, right: 0, left: 0 } : undefined }>
        <StyledContainer size={size}>
            <Box direction="column" pad="large" align="center" background="brand" round={ size === 'small' ? undefined : { corner: 'top', size: '4px' } }>
                <Button plain
                    href={ConfigUtil.get('accounts.home.url')}
                    icon={<Icon size="large" color="white" icon={ConfigUtil.get('accounts.logo.icon')}></Icon>}>
                </Button>
                <Heading level="4" color="white">{intl.formatMessage({ id: 'accounts.logo.label' })}</Heading>
            </Box>
            <Box direction="column" align="center" animation="slideDown">
                <Heading level="6">{intl.formatMessage({ id: 'accounts.quick.login.label' })}</Heading>
                <Nav>
                    {
                        Object.keys(registrations).map(id => (
                            <Button
                                hoverIndicator
                                icon={<Icon icon={registrations[id].icon || registrations[id].clientName} size="large"></Icon>}
                                href={`/oauth2/authorization/${id}${queryStr}`}>
                            </Button>
                        ))
                    }
                </Nav>
            </Box>
            <Box direction="column" fill="horizontal" style={ { position: 'absolute', bottom: 0 } } align="center">
                <LocaleMenu size="small" fontSize="12px"/>
            </Box>
        </StyledContainer>
    </StyledWraper>);

}
Example #22
Source File: mock.ts    From mockiavelli with MIT License 5 votes vote down vote up
private prettyPrint(): string {
        const qs = stringify(this.matcher.query);
        return `(${this.debugId}) ${this.matcher.method || 'HTTP'} ${
            this.matcher.path + (qs ? '?' + qs : '')
        }`;
    }
Example #23
Source File: discord.ts    From workers-queue with MIT License 5 votes vote down vote up
export async function handleDiscord(request: Request, url: URL): Promise<Response> {
    const code = url.searchParams.get('code');

    if (code && code.length < 64) {
        const response = await fetch('https://discordapp.com/api/v6/oauth2/token', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: stringify({
                client_id: DISCORD_CLIENT_ID,
                client_secret: DISCORD_CLIENT_SECRET,
                grant_type: 'authorization_code',
                code,
                redirect_uri: `${url.origin}${url.pathname}`,
                scope: 'identify email connections guilds',
            }),
        });

        switch (response.status) {
            case 200:
                const config = await pullConfig();
                const credentials: DiscordOAuth = await response.json();
                const expiresAt = credentials.expires_in + currentTime();

                const [user, guilds] = await Promise.all([pullUser(credentials), pullUserGuilds(credentials)]);

                if (!user || !guilds) {
                    return ServerError();
                }

                const superUsers = new Set(config.discord.superUsers);

                if (!config.session.enabled && !superUsers.has(user.id)) {
                    return new Response(
                        JSON.stringify({
                            error: 'Session Exists',
                        }),
                        {
                            status: 409,
                        },
                    );
                }

                user.credentials = {
                    access_token: credentials.access_token,
                    refresh_token: credentials.refresh_token,
                    expires_at: expiresAt,
                };

                const sessions = await existingSessions(user);

                if (!sessions) {
                    return ServerError();
                }

                if (sessions.length > 0) {
                    for (const session of sessions) {
                        if (!(await deleteSession(session))) {
                            return ServerError();
                        }
                    }
                }

                const [signedSession, sessionExpiry] = await createSession(request, user, guilds);
                const redirect = await HomeRedirect();
                setCookie(redirect, config.session.cookieName, signedSession, sessionExpiry);

                return redirect;
            case 400 || 401:
                break;
            default:
                return ServerError();
        }
    }

    return handleLogin(request, url);
}
Example #24
Source File: address.ts    From Account-Manager with MIT License 5 votes vote down vote up
formatQueryParams = (params: {[key: string]: any}): string => {
  const queryParams = stringify(params);
  return queryParams.length ? `?${queryParams}` : '';
}
Example #25
Source File: staff.ts    From sidebar with Apache License 2.0 5 votes vote down vote up
StaffModel: StaffModelType = {
  namespace: 'staff',

  state: {},

  effects: {
    *getCurrent(_, { call, put }) {
      const response = yield call(GetCurrentStaff);
      yield put({
        type: 'applyCurrent',
        payload: response.data,
      });
    },
  },

  reducers: {
    applyCurrent(state, action) {
      const params = action.payload as StaffInterface;
      localStorage.setItem(LSExtStaffID, params.ext_staff_id);
      return {
        currentStaff: params || {},
      };
    },

    logout() {
      const { redirect } = getPageQuery();
      localStorage.removeItem(LSExtStaffID);
      // Note: There may be security issues, please note
      if (window.location.pathname !== '/staff-frontend/login' && !redirect) {
        history.replace({
          pathname: '/staff-frontend/login',
          search: stringify({
            redirect: window.location.href,
          }),
        });
      }

      return {
        currentStaff: {},
      };
    },
  },
}
Example #26
Source File: staffAdmin.ts    From dashboard with Apache License 2.0 5 votes vote down vote up
StaffAdminModel: StaffAdminModelType = {
  namespace: 'staffAdmin',

  state: {},

  effects: {
    *getCurrent(_, { call, put }) {
      const response = yield call(GetCurrentStaffAdmin);
      yield put({
        type: 'applyCurrent',
        payload: response.data,
      });
    },
  },

  reducers: {
    applyCurrent(state, action) {
      const params = action.payload as StaffAdminInterface;
      localStorage.setItem(LSExtStaffAdminID, params.ext_staff_id);
      if (params?.role?.permission_ids) {
        setAuthority(params.role.permission_ids);
      }
      return {
        currentStaffAdmin: params || {},
      };
    },

    logout() {
      const { redirect } = getPageQuery();
      localStorage.removeItem(LSExtStaffAdminID);
      // Note: There may be security issues, please note
      if (window.location.pathname !== '/staff-admin/login' && !redirect) {
        history.replace({
          pathname: '/staff-admin/login',
          search: stringify({
            redirect: window.location.href,
          }),
        });
      }

      return {
        currentStaffAdmin: {},
      };
    },
  },
}
Example #27
Source File: index.ts    From game-store-monorepo-app with MIT License 5 votes vote down vote up
stringifyQueryObject = (obj): string => {
  return stringify(removeEmpty(obj));
}
Example #28
Source File: replyMutation.ts    From lexicon with MIT License 5 votes vote down vote up
replyResolver: FieldResolver<'Mutation', 'reply'> = async (
  _,
  { replyInput, file, type, userId },
  context: Context,
) => {
  let replyInputSnake = snakecaseKey({ ...replyInput, archetype: 'regular' });
  const config = {
    headers: {
      'Content-Type': CONTENT_FORM_URLENCODED,
    },
  };

  try {
    if (file) {
      if (type === 'avatar' && !userId) {
        throw new Error('Upload avatar must include user id.');
      }
      const form = new FormData();
      let { createReadStream } = await file;
      let fileStream = createReadStream();
      form.append('files[]', fileStream);
      form.append('type', type);
      if (userId) {
        form.append('user_id', userId);
      }

      const config = {
        headers: {
          ...form.getHeaders(),
        },
      };
      let url = `/uploads.json`;
      let { data } = await context.client.post(url, form, config);
      let {
        originalFilename: name,
        width,
        height,
        shortUrl,
      } = camelcaseKey(data, { deep: true });
      let image = `![${name}|${width} x ${height}](${shortUrl})`;

      replyInputSnake.raw = image + '\n' + replyInputSnake.raw;
    }

    let { data } = await context.client.post(
      '/posts.json',
      stringify(replyInputSnake),
      config,
    );
    return camelcaseKey(data, { deep: true });
  } catch (e) {
    throw errorHandler(e);
  }
}
Example #29
Source File: likePostMutation.ts    From lexicon with MIT License 5 votes vote down vote up
likePostResolver: FieldResolver<'Mutation', 'likePost'> = async (
  _,
  { postId, unlike, postList },
  context: Context,
) => {
  let body = {
    // eslint-disable-next-line @typescript-eslint/camelcase
    post_action_type_id: 2,
  };
  const config = {
    headers: {
      'Content-Type': CONTENT_FORM_URLENCODED,
    },
    params: unlike && body,
  };

  const postConfig = {
    // eslint-disable-next-line @typescript-eslint/camelcase
    params: { post_ids: null, include_raw: true },
  };

  try {
    if (postList) {
      let url = `/t/${postId}.json`;
      let { data: topicDetailResult } = await context.client.get(
        url,
        postConfig,
      );
      let selectedTopic = camelcaseKeys(topicDetailResult, { deep: true });
      let post = selectedTopic.postStream.posts[0];
      postId = post.id;
      let { canUndo, acted } = post.actionsSummary.find(
        (actionSummary: { id: number }) => actionSummary.id === 2,
      );
      if (!canUndo && acted) {
        throw new Error('Already passed the time limit to unlike');
      }
    }
    if (unlike) {
      let { data } = await context.client.delete(
        `/post_actions/${postId}.json`,
        config,
      );
      return camelcaseKeys(data, { deep: true });
    } else {
      Object.assign(body, { id: postId });
      let { data } = await context.client.post(
        `/post_actions.json`,
        stringify(body),
        config,
      );
      return camelcaseKeys(data, { deep: true });
    }
  } catch (e) {
    errorHandler(e);
  }
}