I am not able to use ipfs - blockchain

I want to publish files on ipfs but it's showing me an error.
Here is my code...
const ipfsClient = require('ipfs-http-client');
const ipfs = ipfsClient({host: 'ipfs.infura.io', port: 5001, protocol:
'https'});
function App() {
const [buffer, setBuffer] = useState();
const handleChange = (event) => {
event.preventDefault();
const file = event.target.files[0];
const reader = new window.FileReader();
reader.readAsArrayBuffer(file);
reader.onloadend = () =>{
setBuffer(reader.result);
}
}
const handleSubmit = async(event) => {
event.preventDefault();
console.log('submitting...')
await ipfs.add({buffer}, (error, result) => {
console.log('ipfs results');
if(error){
console.error(error);
return;
}
});
}
I am getting this error in browser...
TypeError: ipfsClient is not a function

Should be some breaking changes. Most probably the copy of the example you have are old version. If you visit the latest readme, the new version should be initiated with:
import { create } from 'ipfs-http-client'
const client = create()
const client = create(new URL('http://127.0.0.1:5002'))
const { cid } = await client.add('Hello world!')
You can rollback to use the old version by specifiying the version no #, i.e. npm install ipfs-http-client#42.0.0. Instead of npm install ipfs-http-client which always pull the latest version (53.X now).
It's also possible to view your installed version in 'package.json' file to see the version you are using and edit with the version you need, 'delete node_modules' folder and re-run npm install. But this requires you to save, which needs a parameter -s, so to run is npm install -s ipfs-http-client
Version 42, sample code should be the one you are using 'https://github.com/ipfs/js-ipfs/tree/v42.0.0'.
Version 53(or the official 1.0 release), tells that there is a breaking change if you visit the official github site; where ipfs-http-client requires a create() and not to be used directly.

I am not familiar with ipfs but i checked the official docs and they have done the first line like this:
const { CID } = require('ipfs-http-client')
Those brackets are essential
What do {curly braces} around javascript variable name mean

Related

Compression (gzip) does not work in NestJS

Created a standard NestJS project using the command: nest new project-name. After that, I installed compression npm i --save compression and plugged it into the project.
import { NestFactory } from '#nestjs/core';
import { AppModule } from './app.module';
import * as compression from 'compression';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.use(compression());
await app.listen(3000);
}
bootstrap();
But the compression does not work, response does not have gzip.
Response in browser
I've already tried clearing the cache, restarting the browser, nothing works.
Thanks for the help
First, install the following package:
npm i --save compression
In the bootstrap function in the main.ts file, apply the compression middleware as follow
async function bootstrap() {
const app: INestApplication = await NestFactory.create(AppModule);
...
app.use(compression({
filter: () => { return true },
threshold: 0
}));
...
await app.listen(4100);
}
Then, you will see the result
Note
if your browser is open, first close it then opens it again
Control+Shift+R or Shift + F5 = Reload your current page, ignoring cached content.
If nothing else works:
const expressApp = express();
expressApp.use(compression());
const expressAdapter = new ExpressAdapter(expressApp);
const app = await NestFactory.create(AppModule, expressAdapter);
await app.listen(3000);

How to initialize ApolloClient in SvelteKit to work on both SSR and client side

I tried but didn't work. Got an error: Error when evaluating SSR module /node_modules/cross-fetch/dist/browser-ponyfill.js:
<script lang="ts">
import fetch from 'cross-fetch';
import { ApolloClient, InMemoryCache, HttpLink } from "#apollo/client";
const client = new ApolloClient({
ssrMode: true,
link: new HttpLink({ uri: '/graphql', fetch }),
uri: 'http://localhost:4000/graphql',
cache: new InMemoryCache()
});
</script>
With SvelteKit the subject of CSR vs. SSR and where data fetching should happen is a bit deeper than with other somewhat "similar" solutions. The bellow guide should help you connect some of the dots, but a couple of things need to be stated first.
To define a server side route create a file with the .js extension anywhere in the src/routes directory tree. This .js file can have all the import statements required without the JS bundles that they reference being sent to the web browser.
The #apollo/client is quite huge as it contains the react dependency. Instead, you might wanna consider importing just the #apollo/client/core even if you're setting up the Apollo Client to be used only on the server side, as the demo bellow shows. The #apollo/client is not an ESM package. Notice how it's imported bellow in order for the project to build with the node adapter successfully.
Try going though the following steps.
Create a new SvelteKit app and choose the 'SvelteKit demo app' in the first step of the SvelteKit setup wizard. Answer the "Use TypeScript?" question with N as well as all of the questions afterwards.
npm init svelte#next demo-app
cd demo-app
Modify the package.json accordingly. Optionally check for all packages updates with npx npm-check-updates -u
{
"name": "demo-app",
"version": "0.0.1",
"scripts": {
"dev": "svelte-kit dev",
"build": "svelte-kit build --verbose",
"preview": "svelte-kit preview"
},
"devDependencies": {
"#apollo/client": "^3.3.15",
"#sveltejs/adapter-node": "next",
"#sveltejs/kit": "next",
"graphql": "^15.5.0",
"node-fetch": "^2.6.1",
"svelte": "^3.37.0"
},
"type": "module",
"dependencies": {
"#fontsource/fira-mono": "^4.2.2",
"#lukeed/uuid": "^2.0.0",
"cookie": "^0.4.1"
}
}
Modify the svelte.config.js accordingly.
import node from '#sveltejs/adapter-node';
export default {
kit: {
// By default, `npm run build` will create a standard Node app.
// You can create optimized builds for different platforms by
// specifying a different adapter
adapter: node(),
// hydrate the <div id="svelte"> element in src/app.html
target: '#svelte'
}
};
Create the src/lib/Client.js file with the following contents. This is the Apollo Client setup file.
import fetch from 'node-fetch';
import { ApolloClient, HttpLink } from '#apollo/client/core/core.cjs.js';
import { InMemoryCache } from '#apollo/client/cache/cache.cjs.js';
class Client {
constructor() {
if (Client._instance) {
return Client._instance
}
Client._instance = this;
this.client = this.setupClient();
}
setupClient() {
const link = new HttpLink({
uri: 'http://localhost:4000/graphql',
fetch
});
const client = new ApolloClient({
link,
cache: new InMemoryCache()
});
return client;
}
}
export const client = (new Client()).client;
Create the src/routes/qry/test.js with the following contents. This is the server side route. In case the graphql schema doesn't have the double function specify different query, input(s) and output.
import { client } from '$lib/Client.js';
import { gql } from '#apollo/client/core/core.cjs.js';
export const post = async request => {
const { num } = request.body;
try {
const query = gql`
query Doubled($x: Int) {
double(number: $x)
}
`;
const result = await client.query({
query,
variables: { x: num }
});
return {
status: 200,
body: {
nodes: result.data.double
}
}
} catch (err) {
return {
status: 500,
error: 'Error retrieving data'
}
}
}
Add the following to the load function of routes/todos/index.svelte file within <script context="module">...</script> tag.
try {
const res = await fetch('/qry/test', {
method: 'POST',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
num: 19
})
});
const data = await res.json();
console.log(data);
} catch (err) {
console.error(err);
}
Finally execute npm install and npm run dev commands. Load the site in your web browser and see the server side route being queried from the client whenever you hover over the TODOS link on the navbar. In the console's network tab notice how much quicker is the response from the test route on every second and subsequent request thanks to the Apollo client instance being a singleton.
Two things to have in mind when using phaleth solution above: caching and authenticated requests.
Since the client is used in the endpoint /qry/test.js, the singleton pattern with the caching behavior makes your server stateful. So if A then B make the same query B could end up seeing some of A data.
Same problem if you need authorization headers in your query. You would need to set this up in the setupClient method like so
setupClient(sometoken) {
...
const authLink = setContext((_, { headers }) => {
return {
headers: {
...headers,
authorization: `Bearer ${sometoken}`
}
};
});
const client = new ApolloClient({
credentials: 'include',
link: authLink.concat(link),
cache: new InMemoryCache()
});
}
But then with the singleton pattern this becomes problematic if you have multiple users.
To keep your server stateless, a work around is to avoid the singleton pattern and create a new Client(sometoken) in the endpoint.
This is not an optimal solution: it recreates the client on each request and basically just erases the cache. But this solves the caching and authorization concerns when you have multiple users.

Ember Super Rentals Tutorial 3.15 - Working with data

I was following the ember Super Rental 3.15 tutorial, when I got to the working with data section, I updated the route index file with model hooks, the page stopped working. Also I am finding ember tutorials to be incomplete.
error says property of map is undefined
code in routes index.js file:
import Route from '#ember/routing/route';
const COMMUNITY_CATEGORIES = [
'Condo',
'Townhouse',
'Apartment'
];
export default class IndexRoute extends Route {
async model() {
let response = await fetch('/api/rentals.json');
let { data } = await response.json();
return data.map(model => {
let { attributes } = model;
let type;
if (COMMUNITY_CATEGORIES.includes(attributes.category)) {
type = 'Community';
} else {
type = 'Standalone';
}
return { type, ...attributes };
});
}
}
image if error message:
Your problem is that fetch('/api/rentals.json'); does not return the correct data. And so when you do let { data } = await response.json(); then data will be undefined and you can not do undefined.map.
So the code you posted is correct. The problem is somewhere else. You can check:
did you correctly add the rentals.json file? If you open http://localhost:4200/api/rentals.json do you see the data? So have you done this?
I see some error from mirage. The super-rentals tutorial does not use mirage. I can see this here (sidenote: that git repo is automatically created from the guides, so its always up to date). So this could be your problem. Depending how you configure mirage it will basically mock all your ajax requests. This means that fetch(... will no longer work then expected, mirage assumes you always want to use mocked data and you did not configure mirage correctly. You can try to remove mirage from your package.json, rerun npm install, restart the ember server and try it again.

Loopback 4: Create seeders to add dummy data in mySQL table

I have been looking around option to create data seeders to add dummy data in my loopback 4 application. However I am not able to find any option in official documentation.
I have found couple of post but those refer to loopback 3, like:
Loopback: Creating a Seed Script
loopback-seed
Please point me out to documentation to do so.
EDIT:
As per suggestion I have created start.js file in scripts folder:
require('babel-register')({
presets: ['es2015']
})
module.exports = require('./seed.js')
And I have copied the script converting it to JavaScript mentioned in seed.js file. When I am running the script, I am getting error:
Cannot find module Models and Repositories
though I have typed correct path.
Actually, I'm doing it with Loopback directly like this (this is typescript):
import * as users from './users.json';
import * as Promise from 'bluebird';
import {Entity, DefaultCrudRepository} from '#loopback/repository';
import {MyApplication} from '../src/application';
import {User} from '../src/models';
import {UserRepository} from '../src/repositories';
const app = new MyApplication();
async function loadByModel<T extends Entity, ID>(items: T[], repository$: DefaultCrudRepository<T,ID>, type: { new(it: Partial<T>): T ;}){
console.log(type.toString());
let repository = await repository$;
await repository.deleteAll();
await Promise.map(items, async (item: T) => {
try{
return await repository.create((new type(item)));
} catch(e){
console.log(item);
}
}, {concurrency: 50});
}
async function load(){
await loadByModel(users, await app.getRepository(UserRepository), User);
}
app.boot().then(async () => {
await load();
console.log('done');
});
We used a separate library db-migrate to keep our migration and seed scripts out of our loopback codebase. Moreso, because db.migrate and db.update methods of juggler are not 100% accurate as mentioned in docs as well. LB4 Database Migrations

Cannot find module '#google-cloud/storage'

I am using the GCP console on my browser. I have created a function as following:
function listFiles(bucketName) {
// [START storage_list_files]
// Imports the Google Cloud client library
const Storage = require('#google-cloud/storage');
// Creates a client
const storage = new Storage();
storage
.bucket(bucketName)
.getFiles()
.then(results => {
const files = results[0];
console.log('Files:');
files.forEach(file => {
console.log(file.name);
});
})
.catch(err => {
console.error('ERROR:', err);
});
// [END storage_list_files]
}
exports.helloWorld = function helloWorld (req, res) {
if (req.body.message === undefined) {
// This is an error case, as "message" is required
res.status(400).send('No message defined!');
}
else {
// Everything is ok
console.log(req.body.lat);
console.log(req.body.lon);
listFiles("drive-test-demo");
res.status(200).end();
}
}
Literally all I am trying to do right now is list the files inside a bucket, if a certain HTTPS trigger comes through.
my package.json file is as follows:
{
"name": "sample-http",
"version": "0.0.1",
"dependencies": {
"#google-cloud/storage": "1.5.1"
}
}
and I am getting the error "Cannot find module '#google-cloud/storage'"
Most queries I have seen thus far have been resolved by using npm install, but I don't know how to do that considering that my index.js and package.json files are stored in a zip file inside a gcloud bucket. Any advice on how to solve this would be much apreciated.
Open console, change dir to you functions project and type:
npm install --save #google-cloud/storage
That's all!