Hello,
I have a big JSON file (about one million lines). The goal is to convert Japanese postcodes to the address, hence I do not need to store the full address in the database, and it's simpler for me to display it in Japanese or Alphabet.
But when I want to load it from my controller, I get an error 500. So I suspect the file is too big (actually the error happens when I try to decode the file).
Then I created a Javascript class (see below) that loads the file within asyn function. So I do not get an error here. However, I can access my object only from app.js, even if I add it to the window variable (see below).
So I have two questions:
- How to access a class I loaded from the
app.js in my project?
- What is the best way to load this file (by JS or PHP)?
Here is what I did with JS:
// inside resources/js
export default class PostalCodeConvertor {
constructor(postalCode=0) {
this.postalCode = postalCode;
this.data = null;
}
// Loading data from JSON
async loadData(postalCode=-1) {
try {
const response = await fetch('/japan_postal_code.json'); // inside public
if (!response.ok) {
console.log("Not loading file");
throw new Error('Couldn\'t load the postal code data.');
}
const jsonData = await response.json();
if(postalCode != -1)
this.postalCode = postalCode;
this.data = jsonData[this.postalCode] || null;
} catch (error) {
console.log("error code");
console.error('Error while loading the postal code:', error);
}
}
// Getters
///...
Here is the code inside app.js with some display of the data (that is working in this file)
import PostalCodeConvertor from './PostalCodeConvertor.js';
window.PostalCodeConvertor = PostalCodeConvertor;
var postalCode = new PostalCodeConvertor("0600042");
postalCode.loadData().then(() => {
console.log('Préfecture (kanji):', postalCode.getPrefKanji());
console.log('Ville/Quartier (kanji):', postalCode.getCityAreaKanji());
console.log('Rue (kanji):', postalCode.getStreetKanji());
console.log('Préfecture (roman):', postalCode.getPrefRoman());
console.log('Ville/Quartier (roman):', postalCode.getCityAreaRoman());
console.log('Rue (roman):', postalCode.getStreetRoman());
});
But when I use it inside app.blade.php, it fails
<!-- ... -->
<head>
@vite(['resources/css/app.css', 'resources/js/app.js'])
</head>
<!-- ... -->
script>
var postalCode = new window.PostalCodeConvertor("0600042");
</script>
Uncaught TypeError: window.PostalCodeConvertor is not a constructor