POST to local json file without server, using Svelte and Routiify - json

Im writing an PWA in Svelte with Routify and im trying to save notes (containing id, title and a body) in a local json file.
Ive been following this code from Svelte REPL (Svelte POST example), but they use an web URL. When trying to use a direct link i get a 404, even tho the path is correct.
<script>
let foo = 'title'
let bar = 'body'
let result = null
async function doPost () {
const res = await fetch('https://httpbin.org/post', {
method: 'POST',
body: JSON.stringify({
foo,
bar
})
})
const json = await res.json()
result = JSON.stringify(json)
}
</script>
<input bind:value={foo} />
<input bind:value={bar} />
<button type="button" on:click={doPost}>
<p>Post it.</p>
</button>
<p>Result:</p>
<pre>
{result}
</pre>
I installed a json server plugin, which kinda worked, but i want to store the data as a local file.
Is it possible to write, using POST to a local json file without using any server?
Is it possible to use relative path when using fetch? Or should i use something else?

Generally, you don't POST data anywhere else but to a server. Having said that, if you absolutely want to save your data using POST, you can add a serviceworker to your app that intercepts the fetch() request and then saves the data in cache, indexeddb, localstorage or something like this. But having that serviceworker in between just for that is a bit silly, you should rather store the data directly in cache, indexeddb or localstorage.
Example for localstorage:
const data = { someKey: { someOtherKey: 'some value' } };
localStorage.setItem('myData', JSON.stringify(data));
Be aware though that, no matter which kind of storage you're using, they all might be wiped out if the user decides to clear browser data or if the browser cleans up by itself due to storage shortage.

Related

how can I make the DOM work with ejs and Mysql

I want to compare "test" with "angendaOficina".
test is a DOM element.
angendaOficina is a table in Mysql database.
When I run the code it tells me that test is not defined and I understand that it is because of the <%%> that I can, but if I remove it, it tells me that document is not defined.
<form name="formulario">
<div><input name="busqueda" placeholder="BUSCAR" required type="text" autofocus></div>
</form>
<div><button id="btn">BUSCAR</button></div>
<script>
function operation() {
var test = document.formulario.busqueda.value;
<% for (var i = 0; i < angendaOficina.length; i++){%>
<%if(angendaOficina[i].carpeta == test){
console.log("MATCH");
}else{
console.log("NO MATCH");
}
%>
<%}%>
}
var btn = document.getElementById("btn");
btn.addEventListener('click', operation, true);
I can't really do exactly what you wanna do, but i can at least help you to solve your problem.
You should not use EJS to import your database like this.
If you want to use your DB data like this, import it in the HTML JavaScript using GET requests.
To do requests you can either use a module like jQuery (which i don't recommend but it is surely the most known) or use the defaults XMLHttpRequest.
You can handle thoses requests in your express server like this :
expressApp.get("/getDatabase", (req, res) => { // "/getDatabase" is the url you wanna GET request.
res.json({
data: dbObject // "dbObject" is your DB data object.
})
})
Then, when you do a request to "/getDatabase" you will get a JSON object that contains data as your database data.

Getting JSON from HTTP Discord.Js

Im making a discord bot, and I have a URL here which has some raw json: link here and I want one of the values (hashrateString) to be put inside a embed like:
hashrateString: 1GH
is there a way to do that and if so how?
I never tried this with an external link but it should work the same way.
FIRST: write somewhere high up in your code this line
var fs = require('fs');
var data = JSON.parse(fs.readFileSync('http://ric.pikapools.com/api/stats', 'utf8'));
After you can basically do whatever you want with your new object. There was no hashrateString: 1GH, but hashrateString: 4.68 GH should be accessible with data.algos.primesr.hashrateString (Output: 4.68 GH)
If it, for some weird reason, doesn't accept an URL, just try to copy&paste the text in a json file if possible, and use the path to it
I was able to get this to work by specifying a constant to be the JSON from the url using node-fetch
const ricp = await fetch('http://ric.pikapools.com/api/stats').then(response => response.json());
and find an object in the JSON using
message.channel.send(ricp.algos.primesr.hashrateString)

Is there a way to send gulp.src(some data) instead of a glob?

I want to be able to edit JSON then send it through the gulp stream. I know there's gulp-json-edit but I want to understand how it's done and do it myself. In this case, to change the Basic authorization.
For example, something like this:
var data = JSON.parse(fs.readFileSync('./core-config.json'));
data.local.ENDPOINT.CORE.BASIC = "Basic Stuff";
gulp.src(data)
.pipe(somestuff)
.pipe(gulp.dest('./'));
However, this of course doesn't work because data isn't a glob. How can I then manipulate data in a way that I can then pass it to gulp.src()?
A while ago I wrote a module that can turn a regular object stream into a vinyl stream: vinylize. It's mostly useful for static site generation, but If I understand your question correctly it should be able to handle your use case as well.
Your example code using vinylize() would look like this:
var vinylize = require('vinylize');
var data = JSON.parse(fs.readFileSync('./core-config.json'));
data.local.ENDPOINT.CORE.BASIC = "Basic Stuff";
vinylize([data], {
path: 'core-config.json',
contents: JSON.stringify(data),
ignoreSourceProps: true,
})
.pipe(somestuff)
.pipe(gulp.dest('./'));

Angular $http not working as expected

I am new to angular and trying to consume a basic back end service that I created using laravel. It is a basic Todo application and I am trying to fetch all the users resource for now.
If you go to the following URI, it will give back the all the users in the application:
Link to the URI
The code in my angular file looks like
var testing = angular.module('testing', []);
testing.controller('MainCtrl', function($scope, $http){
$scope.hello = "Hello World!";
$http.get('users.json').success(function(data){
$scope.users = data;
});
});
Now when I pass the URI in the parameter of $http.get method, I don't see any data. I have tried {{ users | json }} in my main index file to see the dump output. It simply doesn't work. But when I copy just the data array in the response and save it to a json file, it works perfectly.
Now the json that is returned from the web service has slightly more information like status and messages. How do I remove them when fetching them in Angular so that it works or is there a way I can have them returned and then extract them somehow from the whole data that has been returned?
If here http://todoapi.rohanchhabra.in/users is response from your server you should update your $http call to :
$http.get('users.json').success(function(response){
$scope.users = response.data;
});
if you requesting json file from your local iis make sure that it can serve .json files

How to preload JSON data so its available when Angularjs module is ready

I have a very simple app that loads a JSON array using $http.get inside of a controller. It assigns the result data to scope and the HTML repeats through the results to display a list. It is a very simple angularjs example.
function ViewListCtrl($scope, $http) {
$scope.shoppinglist = [];
$scope.loadList = function () {
var httpRequest = $http({
method: 'POST',
url: 'viewList_service.asp',
data: ''
}).success(function (data, status) {
$scope.shoppinglist = data;
});
};
$scope.loadList();
}
While testing on a slow server I realized there was a 3 second blocking delay while rending the repeat region. Debugging revealed to me that my controller does not attempt to get the data until the page is loaded. My page takes 3 seconds to load. Then I must wait another 3 seconds for the json data to load.
I want to load data as soon as possible so it is ready when my controller is ready. Simply put, I want to pre-load the data so it loads in parallel to my module.
I've searched all over and the closest thing I found was "resolve", but I am not using routes. This is a very simple list and no routes or templates.
How can I load the JSON as soon as the page starts to render so it is ready when the controller is ready and there is no blocking... and then get that data into scope?
You can use the module.run method. Which is executed after the config stage is completed. To make use of this you need to create a service factory that does the actual query and caches the result
module("myapp",[]).factory('listService', function($q,$http) {
var listData;
var defer = $q.defer();
return {
loadList: function() {
if(listData) {
defer.resolve(listData);
}
else {
var httpRequest = $http({
method: 'POST',
url: 'viewList_service.asp',
data: ''
})
.success(function(data) {
listData=data;
defer.resolve(listData);
}
}
return defer.promise;
}
}
});
In your controller you still use the factory to get the data with a promise then wrapper.
listService.loadList().then(function(data) {
$scope.shoppinglist=data;
});
This way you can make the async call even before any controller related code executes.
You can load data by writing code (something like Chandermani's listService) in separate file but without using angular. you can use jquery ajax to load your data.
Then write a service in angular to read that data and pass it to your controller.
It sounds like your latency comes from a slow network + server, and not a large amount of data.
So, you could render a tag into your page, so that the data would be sent along with the page HTML response. The downside there is that you're hard-coding your data into your page. This tag would basically pre-seed the $http cache with your data.
var listJson = {...json data here, rendered server-side...};
mod.run(function($cacheFactory) {
var cache = $cacheFactory('yourListCacheId');
cache.put('list-cache-id', listJson);
// store "cache" somewhere you can retrieve it, such as a service or value.
});
Then either use the $http cache property, or wrap $http in a custom service which checks the cache.
Of course, the root of the problem is that your server takes 3 seconds per request, when you normally want that at least in the sub-second range.