Giter VIP home page Giter VIP logo

now-storage's Introduction

Now Storage

Use Now static deployments to upload and store files.

Usage

Install it with yarn

yarn add now-storage

Or with npm

npm i now-storage

Then load it inside your app.

const { upload } = require('now-storage');

And call the upload function with your the Now token and the file to upload.

const { url } = await upload(process.env.NOW_TOKEN, {
  name: 'my-file.txt',
  content: 'This is a file uploaded with now-storage.'
});

The url is going to be a string similar to http://now-storage-bmjowtcani.now.sh/.

Configuration

All the deployments are going to have the name now-storage and the upload function is going to retry maximum 3 times to upload the file and another 3 times to create the deployment.

That could be configured passing a third argument to the upload method with an object using the following format.

await upload(process.env.NOW_TOKEN, {
  name: 'my-file.txt',
  content: 'This is a file uploaded with now-storage.'
}, {
  deploymentName: 'now-storage',
  retry: {
    retries: 3
  }
});

That's the default configuration, the retry key could receive any configuration from async-retry.

To deploy to a team account instead of your personal account add teamId to the config.

await upload(process.env.NOW_TOKEN, {
  name: 'my-file.txt',
  content: 'This is a file uploaded with now-storage.'
}, { teamId: 'my-awsm-team' });

now-storage's People

Contributors

hesselbom avatar michaellopez avatar renovate[bot] avatar sergiodxa avatar zrrrzzt avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

now-storage's Issues

Zeit API does not handle teamId properly

This is a crosspost from #9

As mentioned there I'm opening an issue detailing a bug in the Zeit API for handling team scoped requests.

I send a proper Authorization Bearer token for both of these requests.

Fails:
GET https://api.zeit.co/v2/now/deployments?teamId=<my team slug>

Succeeds:
GET https://api.zeit.co/v2/now/deployments?teamId=<my team ID>

where <my team ID> is the ID I get from GET https://api.zeit.co/teams?slug=<my team slug>. It looks like team_<some hash>.

Let me know if you need anything else @sergiodxa

Update to Now v2

Is your feature request related to a problem? Please describe.

Current implementation uses Now v1.

Describe the solution you'd like

It should be updated to use the Now v2 API with builders

Error: No files in the deployment

I get an error when I try to use this module.

This code

const { upload } = require('now-storage')
const file = {name: 'testfile.txt', content: 'This is my test.... believe it!'}
const STORAGE_TOKEN = 'my-now-token'

async function uploadFile () {
  try {
    const { url } = await upload(STORAGE_TOKEN, {
      name: 'my-file.txt',
      content: 'This is a file uploaded with now-storage.'
    })
    console.log(url)
  } catch (error) {
    console.error(error)
  }
}

uploadFile()

Returns this error

Error: No files in the deployment
    at retry (/node_modules/now-storage/index.js:88:31)
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:188:7)
Error: There was an error while deploying.
    at upload (node_modules/now-storage/index.js:96:11)
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:188:7)

Trying to upload file with React-Dropzone, but I got an error of type file-upload-failed

I don't know if this is a bug, but I'm trying to upload a file with React-Dropzone, with this code:

Component UploadImage:

import React from "react";
import { useDropzone } from "react-dropzone";
import styled from "styled-components";

import CloudUpload from "@material-ui/icons/CloudUpload";

interface IImage {
  image?: string;
  setImage?: Function;
}

const Box = styled.div<IImage>`
  height: 300px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  margin-top: 10px;
  background: ${props => (props.image ? `url(${props.image})` : "white")};
  background-position: center center;
  background-repeat: no-repeat;
  background-size: cover;
  border: rgba(0, 0, 0, 0.54) solid;
  border-style: dashed;
`;

const UploadBox = styled.div`
  text-align: center;
  color: rgba(0, 0, 0, 0.54);

  & > p {
    margin: 0;
  }
`;

export const UploadImage = ({ image, setImage }: IImage) => {
  const { getRootProps, getInputProps } = useDropzone({
    accept: "image/*",
    maxSize: 1.5e7, // 15 mb
    multiple: false,
    onDrop: acceptedFiles => {
      setImage(
        acceptedFiles.map(file =>
          Object.assign(file, {
            preview: URL.createObjectURL(file)
          })
        )
      );
    }
  });

  return (
    <Box {...getRootProps()} image={image}>
      <input {...getInputProps()} />
      <UploadBox>
        <CloudUpload fontSize="large" />
        <p>Upload an image!</p>
      </UploadBox>
    </Box>
  );
};

Then, I use this component to upload the image. This is the route prueba:

import React from "react";
import fetch from "isomorphic-unfetch";

import { UploadImage } from "../components/utils/UploadImage";

const prueba = () => {
  const [state, setState] = React.useState({ image: [] });

  async function handleSendImage(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();

    const response = await fetch("/api/prueba", {
      method: "POST",
      body: JSON.stringify({ file: state.image })
    });

    const json = await response.json();

    console.log(json);
  }

  return (
    <form method="POST" onSubmit={handleSendImage}>
      <UploadImage
        image={state?.image[0]?.preview}
        setImage={(image: File[]) => setState({ image })}
      />

      <button type="submit">DO IT!</button>
    </form>
  );
};

export default prueba;

Then, I create the route (from the api) called /prueba, with this code:

import { NextApiRequest, NextApiResponse } from "next";

import { uploadFile } from "../../lib/uploadFile";

async function prueba(req: NextApiRequest, res: NextApiResponse) {
  const { file } = req.body;

  const response = await uploadFile(file);

  res.json({ response });
}

export default prueba;

and the method uploadFile is this:

import { upload } from "now-storage";

export async function uploadFile(file: File) {
  console.log(file, "upload");

  const { url } = await upload(process.env.NOW_TOKEN, {
    name: "image.png",
    content: file
  });

  return url;
}

But I'm getting this error:

Err [Error]: File upload failed
    at /home/andres/Documents/shooter-app/node_modules/now-storage/lib/try-catch.js:9:21
    at processTicksAndRejections (internal/process/task_queues.js:94:5) {
  type: 'file-upload-failed',
  details: 'https://err.sh/sergiodxa/now-storage/file-upload-failed',
  original: TypeError [ERR_INVALID_ARG_TYPE]: The "data" argument must be one of type string, Buffer, TypedArray, or DataView. Received type object
      at Hash.update (internal/crypto/hash.js:70:11)
      at getSHA (/home/andres/Documents/shooter-app/node_modules/now-storage/lib/get-sha.js:5:10)
      at upload (/home/andres/Documents/shooter-app/node_modules/now-storage/index.js:28:14)
      at /home/andres/Documents/shooter-app/node_modules/now-storage/lib/try-catch.js:6:23
      at uploadFile (/home/andres/Documents/shooter-app/.next/server/static/development/pages/api/prueba.js:113:71)
      at prueba (/home/andres/Documents/shooter-app/.next/server/static/development/pages/api/prueba.js:138:92)
      at Object.apiResolver (/home/andres/Documents/shooter-app/node_modules/next/dist/next-server/server/api-utils.js:42:15)
      at processTicksAndRejections (internal/process/task_queues.js:94:5)
      at async DevServer.handleApiRequest (/home/andres/Documents/shooter-app/node_modules/next/dist/next-server/server/next-server.js:427:9)
      at async Object.fn (/home/andres/Documents/shooter-app/node_modules/next/dist/next-server/server/next-server.js:350:37)
      at async Router.execute (/home/andres/Documents/shooter-app/node_modules/next/dist/next-server/server/router.js:42:32)
      at async DevServer.run (/home/andres/Documents/shooter-app/node_modules/next/dist/next-server/server/next-server.js:468:29) {
    code: 'ERR_INVALID_ARG_TYPE'
  }
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.