How to use ky - 10 common examples

To help you get started, we’ve selected a few ky 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 pizzaql / pizzaql / frontend / pages / home.js View on Github external
size: "${values.size}"
								dough: "${values.dough}"
								name: "${values.name}"
								phone: "${values.phone}"
								time: "${values.time}"
								city: "${values.city}"
								street: "${values.street}"
							}
						) {
							id
						}
					}`;

					try {
						// Post a mutation to Prisma and obtain an ID
						const id = await ky.post('http://localhost:4466', {json: {query}}).json();
						const orderID = JSON.stringify(id.data.createOrder.id);
						// Move user to the thank you page
						Router.push({
							pathname: '/order',
							query: {id: orderID}
						});
					} catch (error) {
						console.log(error);
					}

					// Disable double-submission and reset form
					setSubmitting(false);
					resetForm();
				}, 500);
			}}
github digidem / mapeo-desktop / src / renderer / create-zip.js View on Github external
const tasks = remoteFiles.map(({ url, metadataPath, ...options }) => cb => {
    cb = once(cb)
    const start = Date.now()
    console.log('Requesting', url)
    // I tried doing this by adding streams to the zipfile, but it's really hard
    // to catch errors when trying to download an image, so you end up with
    // corrupt files in the zip. This uses a bit more memory, but images are
    // only added once they have downloaded correctly
    ky.get(url)
      .arrayBuffer()
      .then(arrBuf => {
        console.log('Req end in ' + (Date.now() - start) + 'ms ' + metadataPath)
        zipfile.addBuffer(Buffer.from(arrBuf), metadataPath, {
          ...options,
          store: true
        })
        cb()
      })
      .catch(err => {
        missing.push(metadataPath)
        console.log('Error downloading file ' + metadataPath, err)
        cb()
      })
  })
  const start = Date.now()
github digidem / mapeo-mobile / src / frontend / api.js View on Github external
export function Api({
  baseUrl,
  timeout = DEFAULT_TIMEOUT
}: {
  baseUrl: string,
  timeout?: number
}) {
  let status: ServerStatus = STATUS.STARTING;
  let timeoutId: TimeoutID;
  // We append this to requests for presets and map styles, in order to override
  // the local static server cache whenever the app is restarted. NB. sprite,
  // font, and map tile requests might still be cached, only changes in the map
  // style will be cache-busted.
  const startupTime = Date.now();

  const req = ky.extend({
    prefixUrl: baseUrl,
    // No timeout because indexing after first sync takes a long time, which mean
    // requests to the server take a long time
    timeout: false,
    headers: {
      "cache-control": "no-cache",
      pragma: "no-cache"
    }
  });

  const pending: Array<{ resolve: () => any, reject: Error => any }> = [];
  let listeners: Array<(status: ServerStatus) => any> = [];

  nodejs.channel.addListener("status", onStatusChange);

  function onStatusChange(newStatus: ServerStatus) {
github system-ui / theme-ui / packages / gatsby-plugin-theme-editor / src / edit.js View on Github external
const save = async e => {
    e.preventDefault()
    setStatus('saving')
    const theme = JSON.stringify(context.theme, null, 2)
    const res = await ky.post('/___theme', {
      json: {
        theme,
      },
    })
    if (!res.ok) setStatus('error')
    else setStatus(null)
    // const text = await res.text()
  }
github zero-to-mastery / mappypals / src / store / actions / auth.js View on Github external
(async () => {
            const url = 'http://localhost:3001/users/login';
            await ky
                .post(url, { json: { email, password } })
                .json()
                .then((res, err) => {
                    if (res.token && res.userId) {
                        setLocalData(res.token, res.userId);
                        dispatch(authLoginSucceeded(res.token, res.userId));
                    } else {
                        // error message here
                        dispatch(authLoginFailed(`Error: ${err.statusText}`));
                    }
                })
                .catch(err =>
                    dispatch(
                        authLoginFailed(`Uncaught Error: ${err.statusText}`)
                    )
                );
github pangolinjs / core / ui / src / api / index.js View on Github external
/* globals pangolinBase */

import ky from 'ky'

const connector = ky.create({
  prefixUrl: pangolinBase
})

export default {
  /**
   * Get project information
   */
  getProject () {
    return connector.get('pangolin/project.json').json()
  },
  /**
   * Get template list
   */
  getTemplates () {
    return connector.get('pangolin/templates.json').json()
  },
github xivanalysis / xivanalysis / src / api.ts View on Github external
import ky, {Options} from 'ky'
import _ from 'lodash'
import {Fight, ReportEventsQuery, ReportEventsResponse} from './fflogs'

const options: Options = {
	prefixUrl: process.env.REACT_APP_LOGS_BASE_URL,
}

if (process.env.REACT_APP_LOGS_API_KEY) {
	options.searchParams = {
		api_key: process.env.REACT_APP_LOGS_API_KEY,
	}
}

// Core API via ky
export const fflogsApi = ky.create(options)

async function requestEvents(code: string, searchParams: Record) {
	let response = await fflogsApi.get(
		`report/events/${code}`,
		{searchParams},
	).json()

	// If it's blank, try again, bypassing the cache
	if (response === '') {
		response = await fflogsApi.get(
			`report/events/${code}`,
			{searchParams: {...searchParams, bypassCache: 'true'}},
		).json()
	}

	// If it's _still_ blank, bail and get them to retry
github digidem / mapeo-desktop / src / renderer / new-api.js View on Github external
export function Api ({ baseUrl }) {
  // We append this to requests for presets and map styles, in order to override
  // the local static server cache whenever the app is restarted. NB. sprite,
  // font, and map tile requests might still be cached, only changes in the map
  // style will be cache-busted.
  const startupTime = Date.now()

  const req = ky.extend({
    prefixUrl: baseUrl,
    // No timeout because indexing after first sync takes a long time, which mean
    // requests to the server take a long time
    timeout: false,
    headers: {
      'cache-control': 'no-cache',
      pragma: 'no-cache'
    }
  })

  function logRequest (prefix, promise) {
    const start = Date.now()
    promise
      .then(data => {
        logger.log(prefix, Date.now() - start + 'ms')
      })
github facebook / create-react-app / test / fixtures / builds-with-multiple-runtimes / src / index.js View on Github external
app.router(() => {
  ky.get('https://canihazip.com/s')
    .then(r => r.text())
    .then(console.log, console.error)
    .then(() => console.log('ok'));
  return <div>Test</div>;
});
app.start('#root');
github ralscha / blog2019 / ky / client / src / main.js View on Github external
async function timeout() {
  let response;

  console.log('ky, default, timeout 10s');
  try {
    console.log('request ', Date.now());
    response = await ky.get('http://localhost:8080/timeout');
  } catch (e) {
    console.log('response', Date.now());
    console.log(e);
  }

  console.log('ky, timeout 1s');
  try {
    console.log('request ', Date.now());
    response = await ky.get('http://localhost:8080/timeout', { timeout: 1000 });
  } catch (e) {
    console.log('response', Date.now());
    console.log(e);
  }

  console.log('ky, timeout disabled');
  console.log('request ', Date.now());

ky

Tiny and elegant HTTP client based on the Fetch API

MIT
Latest version published 3 months ago

Package Health Score

94 / 100
Full package analysis