Vue.js and data storing in text/script files - vue.js

I need to store my data in .txt or .json files.
And it's good to load file with axios, for example, and then output the JSON.parsed data.
For example, I have file "data/tweets.json", and there are tons of tweets in json format. Well, I use axios.get ... and then I output content to needed component.
Well, and I cannot use things like import tweets from "#/data/tweets.ts", I need to make something db shaped, but without db engines.
Is there some traditional, easy way to make it?
Maybe there is some kind of node_nodule for the task?
Is there some config for Vue app for the case?

Make an HTTP request to get the static data from your server using Axios or fetch.
axios.get('/data/tweets.json').then((res) => {
// bind your data in Vue
this.tweets = JSON.parse(res.data)
})

Related

How to cache whole next.js's HTML page in Redis?

I'm new to next.js. I'm trying to cache the whole HTML page in next.js. So, that I can reduce the response time in the next call for that page.
I tried by creating a custom server and then save the response that came from rendertoHTML()/render(). But it didn't return any response.
Redis is not for caching whole HTML pages or any other complex object types for that matter. It's key–value database. In Redis you should keep your object simple.
For your case it's best to use stale-while-revalidate (SWR) cache-control headers in combination with getServerSideProps for server-rendering in NextJS.
See here for example.

query to cfscript properly in coldfusion?

CLARIFICATION: The question here is, "how do I stop using <cfquery> to retrieve data and replace it with a call to an API?"
I have a sql query where I need help to convert it to cfscript. However as you can see I have tried converting it. But, I need some verification if I am on the right path to convert from sql query to cfscript. if not, can anyone help me by converting from sql query to cfscript? thanks for the help. here is my code.
CFSCRIPT:
<cfset jsonDatas = fileRead("c:\Users\Desktop\MyApi.json" )>      
<cfset jsonData = deserializeJSON(jsonDatas) />       
<cfif arrayLen(jsonData)>  
<cfloop array="#jsonData#" index="prop">       
<cfoutput>  
<cfscript>  
// writedump(jsonData);for (item in jsonData[1])   {  
  if (#prop.payGrade# == 0) {
         #prop.divisionNbr#;        
 #prop.probationBeginDate#;        
 #prop.legacyStatus#;        
 #prop.payStep#;        
 #prop.creationDate#;           
  } 
I am going to go for broke here. Do you have data in a DB and you just want to return a JSON representation of it? As in
<cfquery name="result">
SELECT ...
FROM whereever
</cfquery>
<cfoutput>#SerializeJSON(result, 'struct')#</cfoutput>
And then something else tries to consume this data? I have been looking and your questions, and I don't know if we are on the generating data side of the world, or in the consuming data side of the world.
You are asking about two different things.
SQL defines the query run on the database.
CFSCRIPT is just a script style syntax for ColdFusion code (as opposed to tags).
Your example code is
Here is some SQL
Here I am reading JSON and converting it to a ColdFusion struct using script style code instead of tags.
Are you trying to go from currently calling a database, which returns data as a ColdFusion query object, to calling an API, which returns data as a JSON packet? You need to then convert the JSON data into the same or similar CF structures you currently use?
UPDATE: If you want to replace the existing query with an API call,
Does the API already exist?
Does it return the same data as the current query?
Is your team moving to APIs to decouple existing code?
Do you need to know HOW to convert a <cfquery> call to an API call?
This is really a comment, but I need a lot of space to write it.
Are you looking to get data from a remote source and display it on a web page. Are you looking to do something like this?
I think we need to clarify which are client side technologies and which are server side technologies.
Update based on comments**
Consider a VueJS solution
<!-- Showing stuff on screen -->
<div id="app">
{{ info }}
</div>
I can show stuff on the screen. This is similar, but not identical to #info#
<!-- Getting data -->
<cfscript>
new Vue({
el: '#app',
data () {
return {
info: null
}
},
mounted () {
axios
.get('https://api.coindesk.com/v1/bpi/currentprice.json')
.then(response => (this.info = response))
}
})
<cfscript>
And this is getting data from a remote source and putting that data into a javascript variable.
Explaination
So why am I doing this with Javascript rather than ColdFusion? Javascript runs on the browser; ColdFusion runs on the server. If you want to consume an API on the browser, you have to use browser based technologies.
My example is in VueJS, but Angular and React are also options. It is a bit dated, but jQuery can do this kind of stuff too.
Code Source: https://v2.vuejs.org/v2/cookbook/using-axios-to-consume-apis.html

Dynamic loading of translations during runtime in VueJS and VueI18n

We're using the VueI18n plugin for internationalizing our Vue application which is working fine so far. Text contents are managed and translated by our editorial staff using Zanata.
However there is a major drawback in our current approach. We're pulling the translations from Zanata during build time, i.e. "baking" them into the application. As a consequence, we need to rebuild and redeploy the application each time a text is edited.
Are there any approaches which pull the translations (or the translation files) when running the application so that the user is always presented the latest content?
You should be able to do this if you load the translation file and then use setLocaleMessage( locale, message ) to load them. I'm assuming you're using axios.
axios.get('/path/to/locale_de')
.then((response) => {
Vuei18nInstance.setLocaleMessage('de', response)
});
The response should be a plain JSON.

Workbox/Vue: Create a custom variation on an existing caching strategy handler

Background:
I'm building an SPA (Single Page Application) PWA (Progressive Web App) using Vue.js. I've a remote PostgreSQL database, serving the tables over HTTP with PostgREST. I've a working Workbox Service Worker and IndexedDB, which hold a local copy of the database tables. I've also registered some routes in my service-worker.js; everything is fine this far....
I'm letting Workbox cache GET calls that return tables from the REST service. For example:
https://www.example.com/api/customers will return a json object of the customers.
workbox.routing.registerRoute('https://www.example.com/api/customers', workbox.strategies.staleWhileRevalidate())
At this point, I need Workbox to do the stale-while-revalidate pattern, but to:
Not use a cache, but instead return the local version of this table, which I have stored in IndexedDB. (the cache part)
Make the REST call, and update the local version, if it has changed. (the network part)
I'm almost certain that there is no configurable option for this in this workbox strategy. So I would write the code for this, which should be fairly simple. The retrieval of the cache is simply to return the contents of the requested table from IndexedDB. For the update part, I'm thinking to add a data revision number to compare against. And thus decide if I need to update the local database.
Anyway, we're now zooming in on the actual question:
Question:
Is this actually a good way to use Workbox Routes/Caching, or am I now misusing the technology because I use IndexedDB as the cache?
and
How can I make my own version of the StaleWhileRevalidate strategy? I would be happy to understand how to simply make a copy of the existing Workbox version and be able to import it and use it in my Vue.js Service Worker. From there I can make my own necessary code changes.
To make this question a bit easier to answer, these are the underlying subquestions:
First of all, the StaleWhileRevalidate.ts (see link below) is a .ts (TypeScript?) file. Can (should) I simply import this as a module? I propably can. but then I get errors:
When I to import my custom CustomStaleWhileRevalidate.ts in my main.js, I get errors on all of the current import statements because (of course) the workbox-core/_private/ directory doesn't exist.
How to approach this?
This is the current implementation on Github:
https://github.com/GoogleChrome/workbox/blob/master/packages/workbox-strategies/src/StaleWhileRevalidate.ts
I don't think using the built-in StaleWhileRevalidate strategy is the right approach here. It might be possible to do what you're describing using StaleWhileRevalidate along with a number of custom plugin callbacks to override the default behavior... but honestly, you'd end up changing so much via plugins that starting from scratch would make more sense.
What I'd recommend that you do instead is to write a custom handlerCallback function that implements exactly the logic you want, and returns a Response.
// Your full logic goes here.
async function myCustomHandler({event, request}) {
event.waitUntil((() => {
const idbStuff = ...;
const networkResponse = await fetch(...);
// Some IDB operation go here.
return finalResponse;
})());
}
workbox.routing.registerRoute(
'https://www.example.com/api/customers',
myCustomHandler
);
You could do this without Workbox as well, but if you're using Workbox to handle some of your unrelated caching needs, it's probably easiest to also register this logic via a Workbox route.

How to work with local versions of data objects within a Vue.js application?

I'm using Vue.js and vuex to work with data from a backend store that I access via and api.
My question may be more about semantics and how to actually ask this question and search for better answers because I don't even know the correct terms to be searching on. So here goes...
Within my vue code I make a call to my back end api and it returns a json blob with a block of data that i want to work with in the ui. No problems there. But then I need to slightly modify that data to present it to the user. this entails assessing a few fields and changing them (say, if the value is 0 put in 'n/a', etc.), maybe doing some math on a few fields and so on. Then I present that to the user in a grid/table. I want the user to be able to sort and search on the fields as well. So I may display a field named fullName that comes from the back end but allow the user to sort on a field named lastName that is not actually in the grid.
With that said, here is my question - should I be creating a single 'transformer/reducer' in code to translate the data object coming from the api into what I need for the ui? Or should I be writing multiple filters (by this I mean Vue.js filters that go directly in the html with the '|' pipe) to just modify the fields directly in the html template?
My concern is the once i modify the object coming back from the api what if I have to post/patch/put back some kind of update - then I need a 'reverse' transformer to get back to an object that my api wants to see.
Generically, I suppose my question could be boiled down to "how do I locally handle an api response object so that I can maintain its 'purity'?"
Or something along those lines. I'm obviously fumbling for the correct terms and that is why i'm struggling to even google for info on this topic. For that I apologize and any help would be appreciated.
Also, I realize there is nothing Vue-specific about my question as this issue could apply to any data-driven ui framework.
I think I get what you're asking now. You just want to know if you need to modify the response before making it consumable by the UI. Let's say you're using axios. What I would do in Vue is use the response.data object as the data to inject into the vue data property. For example, your response.data returns an array of objects. You would hardcode a data variable in Vue like this:
data () {
return {
apiData: []
}
}
and with the API response, set the data array like this:
const response = await axios.get(...);
this.apiData = response.data.filter(item => return item.foo === bar);
Now apiData holds a filtered version of the response data, which was asynchronously retrieved for processing, including the ObjectId's for each object. Note: I would call this during created(){} hook to allow time for the GET request to process prior to DOM mounting.You can reference the array objects by the ObjectID within the UI, like this:
<div v-for="item in apiData" :key='item_id' :item="item">
<p> {{item.whateverProperty}} </p>
</div>