Using Loopback 4, I am trying to execute a simple get request after which I want to store some data in my database.
I would like to execute the following code from the command line:
import {WebshopApplication} from '../application';
import axios from 'axios';
import {CurrencyRepository} from '../repositories';
export async function importCurrencies(args: string[]) {
const app = new WebshopApplication();
await app.boot();
const host = 'http://data.fixer.io/api';
const accessToken = 'access_key=mykey';
const currencyRepository = await app.getRepository(CurrencyRepository);
const currencies = currencyRepository.find({});
console.log(currencies);
try {
const resp = await axios.get(`${host}/latest?${accessToken}` );
const currencies = resp.data;
console.log(currencies);
} catch (err) {
console.log(err);
}
process.exit(0);
}
importCurrencies(process.argv).catch(err => {
console.error('Cannot import currencies due to error', err);
process.exit(1);
});
When i execute:
ts-node src/commands/import-currency.command.ts
I get the following error:
Cannot import currencies due to error Error: The key 'repositories.CurrencyRepository' is not bound to any value in context WebshopApplication-f9b12a86-ec04-46b4-8e87-4031a4ab71f9
Why is this not working?
UPDATE 26-05-2020:
I have updated the above script to the following as per a suggestion in the commands.
import {WebshopApplication} from '../application';
import axios from 'axios';
import {CurrencyRepository} from '../repositories';
import {bind, BindingScope} from '@loopback/context';
@bind({scope: BindingScope.TRANSIENT})
export class ImportCurrencies {
generate = async () => {
const app = new WebshopApplication();
await app.boot();
const host = 'http://data.fixer.io/api';
const accessToken ='mytoken';
const currencyRepository = await app.getRepository(CurrencyRepository);
const currencies = currencyRepository.find({});
const resp = await axios.get(`${host}/latest?${accessToken}`);
const currencies = resp.data;
process.exit(0);
}
}
const importCurrencies = new ImportCurrencies();
importCurrencies.generate().catch(err => {
process.exit(1);
});
Unfortunately adding the binding at the top of the class did not work