Giter Club home page Giter Club logo

Comments (9)

elitan avatar elitan commented on May 29, 2024

Thanks for this issue. Did you initialize nhost like this: https://github.com/nhost/nhost-js-sdk#setup

We have not done much testing with Nhost on React Native yet. Right now we focus on getting things stabile with Web (React, NextJS, Vue, NuxtJS etc).

React Native is still a few weeks away, just so you know.

from nhost-js-sdk.

Svarto avatar Svarto commented on May 29, 2024

Thanks a lot Johan, I did initialize it as you mentioned however still getting the error. I will for now use the sdk for auth and wait with the storage and try the old "fashioned way" with fetch / axios.

Happy to be a tester / support as I can when you start working on react-native!

from nhost-js-sdk.

elitan avatar elitan commented on May 29, 2024

OK. then your import is incorrect I think:

import { storage } from "nhost-js-sdk";

It should be something like import { storage } from './nhost.js

In ./nhost.js your should initialize your app.

from nhost-js-sdk.

Svarto avatar Svarto commented on May 29, 2024

@elitan yes! that was exactly it. Thank you.

Now the request is going through to the server, however I keep getting a 404 Not Found error. I tried with a standard axios post as well and I get the same 404 Not Found error - so something must be off with how I format the upload. But I can't figure out what...

The 404 error message:

Error: Not Found
    at /app/dist/routes/index.js:21:26
    at Layer.handle [as handle_request] (/app/node_modules/express/lib/router/layer.js:95:5)
    at trim_prefix (/app/node_modules/express/lib/router/index.js:317:13)
    at /app/node_modules/express/lib/router/index.js:284:7
    at param (/app/node_modules/express/lib/router/index.js:354:14)
    at param (/app/node_modules/express/lib/router/index.js:365:14)
    at Function.process_params (/app/node_modules/express/lib/router/index.js:410:3)
    at next (/app/node_modules/express/lib/router/index.js:275:10)
    at /app/node_modules/express/lib/router/index.js:635:15
    at next (/app/node_modules/express/lib/router/index.js:260:14)
    at /app/node_modules/express/lib/router/index.js:635:15
    at next (/app/node_modules/express/lib/router/index.js:260:14)
    at Function.handle (/app/node_modules/express/lib/router/index.js:174:3)
    at router (/app/node_modules/express/lib/router/index.js:47:12)
    at Layer.handle [as handle_request] (/app/node_modules/express/lib/router/layer.js:95:5)
    at trim_prefix (/app/node_modules/express/lib/router/index.js:317:13) {
  data: null,
  isBoom: true,
  isServer: false,
  output: {
    statusCode: 404,
    payload: { statusCode: 404, error: 'Not Found', message: 'Not Found' },
    headers: {}
  }
}
POST /storage/o/default_images/test_image.jpg 404 60 - 3.116 ms

The latest code:
//Nothing changed above or below this:

    try {
      data = await storage.put(
        "/default_images/test_image.jpg",
        result.uri,
        null,
        (d) => console.log(d)
      );
    } catch (e) {
      console.log(result.uri);
      console.log(e);
    }
  };

My HBP table: IMGUR LINK

from nhost-js-sdk.

elitan avatar elitan commented on May 29, 2024

OK. good. Now the issue is probably with your storage rules. How does your rules.yaml file look like in ./custom/storage-rules/rules.yaml? Or are you using Nhost for your backend? then the storage rules can be edited under Storage -> Rules.

from nhost-js-sdk.

elitan avatar elitan commented on May 29, 2024

Just a note: The storage is completely decoupled from the data/api. If you want to save information about files in the database, you need to do that insertion after the file has been uploaded.

from nhost-js-sdk.

Svarto avatar Svarto commented on May 29, 2024

Currently I am trying out HBP on my home LAN, so using the docker-compose.yml. Ok that is good to know about the database/api and the s3 storage.

What I can see though is that the connection to the backend s3 storage goes through HBP, so the storage rules are managed by HBP correct? i.e. the minio instance accepts all uploads, however they are piped through HBP and that is where the authentication / storage rules are controlled?

My storage_rules:

functions:
  isAuthenticated: 'return !!request.auth'
  isOwner: "return !!request.auth && userId === request.auth['user-id']"
  validToken: 'return request.query.token === resource.Metadata.token'
paths:
  /user/:userId/:
    list: 'isOwner(userId)'
  /user/:userId/:fileId:
    read: 'isOwner(userId) || validToken()'
    write: 'isOwner(userId)'

I assume I need to add in the paths I want, so if I have another public folder then that need to be a separate path? Do you have any links or resources to read up on the storage_rules syntax / options?

from nhost-js-sdk.

elitan avatar elitan commented on May 29, 2024

You are right. What you can do as a starter is to apply the following rules.yaml:

functions:
  isAuthenticated: 'return !!request.auth'
  isOwner: "return !!request.auth && userId === request.auth['user-id']"
  validToken: 'return request.query.token === resource.Metadata.token'
  public: 'return true' 
paths:
  /public*:
    read: 'public()'
    write: 'public()'
  /user/:userId/:
    list: 'isOwner(userId)'
  /user/:userId/:fileId:
    read: 'isOwner(userId) || validToken()'
    write: 'isOwner(userId)'

Then make sure to restart HBP.

Then upload a file to /public/test_image.jpg.

Unfortunately we don't have much documentation about this yet (https://nhost.github.io/hasura-backend-plus/configuration.html#storage-rules)

from nhost-js-sdk.

Svarto avatar Svarto commented on May 29, 2024

Got it to work, here is the code that works in react-native. Had to pass in a slightly different format for the file, than what is done on the web. Using the documentation sample code of imagepicker, and combining it with the nhost-js-sdk to upload a image to


import React, { useState, useEffect } from "react";
import { Button, Image, View, Text } from "react-native";
import * as ImagePicker from "expo-image-picker";
import Constants from "expo-constants";
import { storage, auth } from "../services/nhost_sdk";

export default function ImagePickerExample() {
  const [image, setImage] = useState(null);

  useEffect(() => {
    (async () => {
      if (Constants.platform.ios) {
        const {
          status,
        } = await ImagePicker.requestCameraRollPermissionsAsync();
        if (status !== "granted") {
          alert("Sorry, we need camera roll permissions to make this work!");
        }
      }
    })();
  }, []);

  const pickImage = async () => {
    let result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.All,
      allowsEditing: true,
      quality: 1,
      base64: true,
    });

    if (!result.cancelled) {
      setImage(result.uri);
    }
    // nhost-js-sdk code uploading a file called default_avatar.png to /public/default_avatar.png
    try {
      let data = await storage.put(
        "/public/default_avatar.png",
        { uri: result.uri, name: "default_avatar.png", type: "image/png" },
        null,
        (d) => console.log(d)
      );
      console.log(data);
    } catch (e) {
      console.log(e);
    }
  };

  const requestMetadata = async () => {
    let metadata = await storage.getMetadata("/public/");
    console.log(metadata);
  };

  return (
    <View
      style={{ flex: 1, alignItems: "center", justifyContent: "space-around" }}
    >
      <Button title="Pick an image from camera roll" onPress={pickImage} />
      {image && (
        <Image source={{ uri: image }} style={{ width: 200, height: 200 }} />
      )}
      <Button title="Get the metadata folder!" onPress={requestMetadata} />
      <Text>This is the picture from my server</Text>
      <Image
        source={{
          uri:
            "https://minio.svarto-server.com/storage/o/public/test_image3.jpg?token=886e1e69-34ec-464a-a4bd-58334e8ce5bd",
        }}
        style={{ width: 200, height: 200 }}
      />
    </View>
  );
}

from nhost-js-sdk.

Related Issues (20)

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.