Nuxt-i18n: how to load messages asynchronously? - javascript

I am building a multilingual Nuxt web app.
Using this example from the official documentation (Codepen link), I no longer want to use local JSON files where my translations are saved to work as defined in the code below:
messages: {
'en': require('~/locales/en.json'), # I want to get this asynchronously from an HTTP URL
'fr': require('~/locales/fr.json') # I want to get this asynchronously from an HTTP URL
}
I wonder what available alternatives to set asynchronously en and fr values by reading the JSON data from a URL instead?
plugins/i18n.js:
import Vue from 'vue'
import VueI18n from 'vue-i18n'
Vue.use(VueI18n)
export default ({ app, store }) => {
// Set i18n instance on app
// This way we can use it in middleware and pages asyncData/fetch
app.i18n = new VueI18n({
locale: store.state.locale,
fallbackLocale: 'en',
messages: {
'en': require('~/locales/en.json'), # How to get this asynchronously?
'fr': require('~/locales/fr.json') # # How to get this asynchronously?
}
})
app.i18n.path = (link) => {
if (app.i18n.locale === app.i18n.fallbackLocale) {
return `/${link}`
}
return `/${app.i18n.locale}/${link}`
}
}
What I tried:
messages: {
'en': axios.get(url).then((res) => {
return res.data
} ),
'fr': require('~/locales/fr.json')
}
Where url points to the /locals/en.json file which is hosted on my Github profile.

You can use axios with await directly in the constructor:
export default async ({ app, store }) => {
app.i18n = new VueI18n({ //construction a new VueI18n
locale: store.state.i18n.locale,
fallbackLocale: 'de',
messages: {
'de': await axios.get('http://localhost:3000/lang/de.json').then((res) => {
return res.data
}),
'en': await axios.get('http://localhost:3000/lang/en.json').then((res) => {
return res.data
})
}
})
}

I've a solution with localise.biz and cross-fetch
First add async to the pluginsplugins / i18n.js function and add await to the remote translation calls :
import Vue from 'vue';
import VueI18n from 'vue-i18n';
import getMessages from './localize';
Vue.use(VueI18n);
export default async ({ app, store }) => {
app.i18n = new VueI18n({
locale: store.state.locale,
fallbackLocale: 'en',
messages: {
'en': await getMessages('en'),
'fr': await getMessages('fr')
}
});
app.i18n.path = (link) => {
if (app.i18n.locale === app.i18n.fallbackLocale) return `/${link}`;
return `/${app.i18n.locale}/${link}`;
}
}
And create new function for get remote translation :
import fetch from 'cross-fetch';
const LOCALIZE_API_KEY = 'XXXXXXXXXXX';
const LOCALIZE_URL = 'https://localise.biz/api/export/locale';
const HEADERS = {
'Authorization': `Loco ${LOCALIZE_API_KEY}`
};
const getMessages = async (locale) => {
const res = await fetch(`${LOCALIZE_URL}/${locale}.json`, { headers: HEADERS });
if (res.status >= 400) throw new Error("Bad response from server");
return await res.json();
};
export default getMessages;

This is what i ended up with:
async asyncData(context){
// fetch translation for your source
var translation = await fetch('/translation')
// get locale of current page
var locale = context.app.i18n.locale
// set translation for Server Side Rendering
context.app.i18n.mergeLocaleMessage(locale, translation)
// save it for use on client side
return {translation: translation}
},
created(){
// prevent reverting back to not found after hard-loading page.
this.$i18n.mergeLocaleMessage(this.$i18n.locale, this.translation)
}

Related

Call external API in Firebase Cloud Function returns null

I'm trying to call a simple api to currency conversion in Firebase Cloud Function in Typescript, but always it returns 'null'
import { https } from 'firebase-functions';
import * as axios from 'axios';
import * as cors from 'cors';
export const createTransfer = async (amount: number) => {
https.onRequest((req, res) => {
cors({origin: true})(req, res, () => {
const config = {
headers: {
apikey: 'APIKEY',
},
params: {
to: 'USD',
from: 'ILS',
amount: amount
}
};
const convert = axios.default.get('https://api.apilayer.com/exchangerates_data/convert', config)
.then((resp) => {
res.send(resp.data);
})
.catch((error) => {
res.sendStatus(error);
});
return convert;
});
});
};
/////// DEPLOYABLE FUNCTION ////////
export const stripeTransferPayment = https.onCall( async (data, context) => {
const amount = assert(data, 'amount');
return createTransfer(amount);
});
It should return the converted amount. Where am I doing wrong and how can I solve this?
It looks like your line return convert; returns the value before it is ever assigned. Try awaiting on your request:
const convert = await axios.default.get('https://api.apilayer.com/exchangerates_data/convert', config);
res.send(convert.data)
According to the docs at https://apilayer.com/marketplace/exchangerates_data-api I don't think you are providing the proper parameters in the request. First, it looks like you are attempting to convert the value in today's terms, but the endpoint you're using is for historical data. This probably isn't really a problem, and I'd expect you can continue using this endpoint if you also send it today's date. However, if you are trying to get a conversion for today, I would suggest using the https://api.apilayer.com/exchangerates_data/live endpoint instead.
According to the docs, the proper parameter names are "base" and "symbols", not "from" and "to" (respectively). Try this:
// ...
https.onRequest((req, res) => {
cors({origin: true})(req, res, () => {
const config = {
headers: {
apikey: 'APIKEY', // ensure this is actually your API key in your code, good on you for not exposing it publicly ;)
},
params: {
base: 'USD',
symbols: 'ILS',
amount: amount
}
};
const convert = axios.default.get('https://api.apilayer.com/exchangerates_data/live', config)
.then((resp) => {
res.send(resp.data);
})
.catch((error) => {
res.sendStatus(error);
});
return convert;
});
});
// ...

Sveltekit Error: `page` in `load` functions has been replaced by `url` and `params`

I am trying to display my date from GraphCMS in my blog application. I receive this error when I go to my single post link (http://localhost:3000/posts/union-types-and-sortable-relations)
"
page in load functions has been replaced by url and params
Error: page in load functions has been replaced by url and params
"
Here is my code
<script context='module'>
export const load = async ({fetch, page: {params}}) => {
const {slug} = params
const res = await fetch(`/posts/${slug}.json`)
if(res.ok) {
const {post} = await res.json()
return {
props: {post},
}
}
}
</script>
<script>
export let post
</script>
<svelte:head>
<title>Emrah's Blog | Welcome</title>
</svelte:head>
<pre>{JSON.stringify(post, null, 2)}</pre>
Can you please help. Thanks
Try using params instead of page: params, though the latter still works in Sveltekit 278 (which I'm using).
Besides, I'm curious to know what makes you prefer this method to querying GraphCMS for your single post. I do it like this:
import {client} from '$lib/js/graphql-client'
import {projectQuery} from '$lib/js/graphql-queries'
export const load = async ({ params }) => {
const {slug} = params
const variables = {slug}
const {project} = await client.request(projectQuery, variables)
return {
props: {
project
}
}
}
Yes, this has been changed a while ago, now the different parts of what used to be page are passed directly into the load function:
export async function load({ fetch, page }) {
const { params, url } = page
}
export async function load({ fetch, params, url }) {
}
Something else to consider is that now there are page endpoints, if your file is [slug].svelte you can make a file [slug].js and add the following:
export async function get({ params }) {
const { slug } = params;
const post = {}; // add the code to fetch from GraphCMS here
return {
status: 200,
body: {
post
}
}
}
With this you can remove the load function and make your code simpler (especially because you technically already have all this code in your /posts/[slug].json.js file.
<script context='module'>
export async function load({ fetch, params}){
let id = params.users
const response = await fetch(`https://jsonplaceholder.typicode.com/users/${id}`)
const user = await response.json()
if(response.ok){
return {props:{user}}
}
return {
status: response.status,
error : new Error(" sorry no user found")
}
}
export let user

SvelteKit: How to call mongodb without using endpoints?

(1/9/2023) Update : SvelteKit now supports server only load functions and Form actions to send requests to the server.
I want to call my database, but I don't want it be able to get accessed by end users by them going to the API endpoint that I set up. I was wondering how I would be able to just call my database from a file in the lib folder and just returning the data there. When I try it I get the error global not defined:
lib/db.js:
import dotenv from "dotenv";
dotenv.config();
import { MongoClient } from "mongodb";
const uri = process.env["MONGODB_URI"];
const options = {
useUnifiedTopology: true,
useNewUrlParser: true,
};
let client;
let clientPromise;
if (!uri) {
throw new Error("Please add your Mongo URI to .env.local");
}
if (process.env["NODE_ENV"] === "development") {
if (!global._mongoClientPromise) {
client = new MongoClient(uri, options);
global._mongoClientPromise = client.connect();
}
clientPromise = global._mongoClientPromise;
} else {
client = new MongoClient(uri, options);
clientPromise = client.connect();
}
export default clientPromise;
routes/items/index.js:
import clientPromise from "$lib/db";
export async function get() {
const client = await clientPromise;
const db = client.db();
const data = await db.collection("items").find({}).toArray();
const items = data.map(({ name }) => ({ name }));
if (items) {
return {
body: {
items,
},
};
}
}
My attempt:
lib/stores/items.js
import clientPromise from "$lib/db";
import { writable } from "svelte/store";
export const items= writable([]);
const fetchItems = async () => {
const client = await clientPromise;
const db = client.db();
const data = await db.collection("items").find({}).toArray();
const items = data.map(({ name }) => ({ name }));
substances.set(items);
};
fetchItems();
Trying the above code in various places always yields a global not defined error in the client.
I found one question from someone with the same problem, but I couldn't figure out how to create a helper file.
Protecting API is done on back-end side. Usually it either server (like NodeJS) or tools Nginx/Apache (proxy, etc.). You're basically looking for Content-Security-Policy topic, which is vaporous but not related to SvelteKit.
Btw, calling DB directly from the Front-end wouldn't be secure and is not possible.
To get data from any database, you should create enpoint
For user authentication, you can create handle hook:
export async function handle({ request, resolve }) {
let user = await authenticate(request)
request.locals.user = user
request.locals.isAuthenticated = !!user
if (request.path.startsWith('/api')) {
if (!user) {
return {
status: 401,
body: JSON.stringify({
error: {
message: 'Unauthorized'
}
})
}
}
const response = await resolve(request)
return response
}

Nuxt auth update auth on custom requests

From nuxt auth website I saw this:
setUserToken(token)
Returns: Promise
Set the auth token and fetch the user using the new token and current strategy.
TIP: This function can properly set the user after registration
this.$auth.setUserToken(token)
.then(() => this.$toast.success('User set!'))
Tried to use it and it said method is undefined, looked up in the source files and none of methods are like this one.
I am not very good with this but, how would I set user and token with nuxt/auth module after registration or anything but login/loginWith?
If there is no option for that why is it there on documentation?
I would also need to know if I need to create custom auth do I need to use both cookies and localstorage or just one of them?
It says that cookies are used for server side and storage for client side.
Can I use just cookies and on nuxtServerInit get cookie for token and set token and user data fetched by api within vuex store? Then use it from there if it is needed?
Nuxt/auth module hurt my brain so long and today I created custom module:
First I have this store structure:
store/
-- index.js
-- mutations.js
-- actions.js
-- state.js
-- getters.js
middleware/
-- redirectIfAuth.js
-- redirectIfNotAuth.js
layouts/
default.vue -> has redirectIfNotAuth.js
guest.vue -> has redirectIfAuth.js
pages/
-- login/
---- index.vue -> uses guest.vue as layout
-- dashboard/
----- index.vue -> uses default.vue as layout without declaration
Inside Index.js I have:
import state from './state'
import * as actions from './actions'
import * as mutations from './mutations'
import * as getters from './getters'
export default {
state,
getters,
mutations,
actions,
modules: {}
}
Inside State.js I have:
export default () => ({
user: null,
token: null,
headers: null
})
Inside Actions.js I have:
const cookieparser = process.server ? require('cookieparser') : undefined
// importing server based cookie library
export async function nuxtServerInit ({ commit }, { req, res }) {
// If we have any axios requests we need to add async/await
// And since this works on server mode, we don't need to check is it server
let token = null
if (req.headers.cookie) {
const parsed = cookieparser.parse(req.headers.cookie)
try {
token = parsed.authToken
} catch (e) {
console.log(e)
}
}
// If we have token within cookies we get user data from api and we pass Autorization headers with token
if (token !== null && token !== false) {
await axios.get('/api/auth/me', {
headers: {
'Authorization': token
}
}).then((response) => {
// If we get user data we set it to store
commit('setUser', response.data.data)
commit('setToken', token)
commit('setHeaders', token)
}).catch((error) => {
// If we get error, we should logout user by removing data within cookies and store
// Additionally you can create specific code error on backend to check if token is expired or invalid
// and then check for status code and then remove data
commit('setUser', null)
commit('setToken', null)
res.setHeader('Set-Cookie', [`authToken=false; expires=Thu, 01 Jan 1970 00:00:00 GMT`])
// This is only way I found useful for removing cookies from node server
console.warn(error)
})
}
}
Inside Mutations.js I have:
export const setToken = (state, payload) => state.token = payload
export const setUser = (state, payload) => state.user = payload
export const setHeaders = (state, payload) => {
state.headers = {
headers: {
'Authorization': payload
}
}
}
Inside Getters.js I have:
export const getUser = (state) => state.user
export const getToken = (state) => state.token
export const getHeaders = (state) => state.headers
Second I created two middlewares and it seems like nuxt middlewares work on both server and client sides, so I needed to require both libraries for server and client side Then I checked which side it is and then try to get token for further investigations If you include and don't check for server and client but use one of them, your templates wont render but show undefined errors for req on client instead and on server it wont show anything.
Inside redirectIfAuth.js I have:
const cookieparser = process.server ? require('cookieparser') : undefined
const Cookie = process.client ? require('js-cookie') : undefined
export default function ({ app, redirect, req }) {
let token = null
if (process.server) {
if (req.headers.cookie) {
const parsed = cookieparser.parse(req.headers.cookie)
try {
token = parsed.authToken
} catch (e) {
console.log(e)
}
}
} else if (process.client) {
token = Cookie.get('authToken')
}
if (token && token !== false) {
app.store.commit('setToken', token)
app.store.commit('setHeaders', token)
if (app.store.state.user) {
if (app.store.state.user.roles.includes('customer')) {
return redirect({
name: 'customer-slug',
params: { slug: app.store.state.user.username }
})
} else if (app.store.state.user.roles.includes('admin')) {
return redirect({
name: 'dashboard'
})
} else {
return redirect({
name: 'index'
})
}
} else {
return redirect({
name: 'index'
})
}
}
}
Inside redirectIfNotAuth.js I have:
const cookieparser = process.server ? require('cookieparser') : undefined
const Cookie = process.client ? require('js-cookie') : undefined
export default function ({ app, redirect, route, req }) {
let token = null
if (process.server) {
if (req.headers.cookie) {
const parsed = cookieparser.parse(req.headers.cookie)
try {
token = parsed.authToken
} catch (e) {
console.log(e)
}
}
} else if (process.client) {
token = Cookie.get('authToken')
}
if (token === null || token === false) {
return redirect({
name: 'login',
query: {
redirect: route.fullPath
}
})
}
}
Now we use these middlewares within pages or layouts as:
export default {
middleware: ['redirectIfAuth']
}
Or
export default {
middleware: ['redirectIfNotAuth']
}
Login:
async login () {
if (this.form.email !== '' && this.form.password !== '') {
await this.$axios.post('/api/auth/login', this.form).then((response) => {
this.$store.commit('setUser', response.data.data)
this.$store.commit('setToken', 'Bearer ' + response.data.meta.access_token)
this.$store.commit('setHeaders', 'Bearer ' + response.data.meta.access_token)
Cookie.set('authToken', 'Bearer ' + response.data.meta.access_token, { expires: 365 })
// Cookie.set('authUser', response.data.data, { expires: 365 }) if you need user data within cookies
if (this.$route.query.redirect) {
this.$router.push(this.$route.query.redirect)
}
this.$router.push('/')
})
}
}
Logout:
async logout () {
await this.$axios.post('/api/auth/logout', {}, this.headers)
// Cookie.remove('authUser') if exists
Cookie.remove('authToken')
this.$router.push('/')
}
I hope this helps someone or someone get idea from this to make something else. I had million problems with official nuxt auth and only this helped me sort things out...

vue-apollo 3.0.0 Beta configuration

Pretty new at this so any help much appreciated.
I know how to do Authentication with Apollo client but when I add to my Vue-cli-3 generated project the new vue-apollo-plugin (https://www.npmjs.com/package/vue-apollo). I don't understand how and where to configure my authMiddleware.
Here is the auto generated file form the the cli:
import Vue from 'vue'
import VueApollo from 'vue-apollo'
import { createApolloClient, restartWebsockets } from 'vue-cli-plugin-apollo/graphql-client'
// Install the vue plugin
Vue.use(VueApollo)
// Name of the localStorage item
const AUTH_TOKEN = 'apollo-token'
// Config
const defaultOptions = {
httpEndpoint: process.env.VUE_APP_GRAPHQL_HTTP || 'http://localhost:4000', // Use `null` to disable subscriptions
wsEndpoint: process.env.VUE_APP_GRAPHQL_WS || 'ws://localhost:4000',
// LocalStorage token
tokenName: AUTH_TOKEN,
// Enable Automatic Query persisting with Apollo Engine
persisting: false,
// Use websockets for everything (no HTTP)
// You need to pass a `wsEndpoint` for this to work
websocketsOnly: false,
// Is being rendered on the server?
ssr: false,
// Additional ApolloClient options
// apollo: { ... }
// Client local data (see apollo-link-state)
// clientState: { resolvers: { ... }, defaults: { ... } }
}
// Call this in the Vue app file
export function createProvider (options = {}) {
// Create apollo client
const { apolloClient, wsClient } = createApolloClient({
...defaultOptions,
...options,
})
apolloClient.wsClient = wsClient
// Create vue apollo provider
const apolloProvider = new VueApollo({
defaultClient: apolloClient,
defaultOptions: {
$query: {
// fetchPolicy: 'cache-and-network',
},
},
errorHandler (error) {
// eslint-disable-next-line no-console
console.log('%cError', 'background: red; color: white; padding: 2px 4px; border-radius: 3px; font-weight: bold;', error.message)
},
})
return apolloProvider
}
// Manually call this when user log in
export async function onLogin (apolloClient, token) {
localStorage.setItem(AUTH_TOKEN, token)
if (apolloClient.wsClient) restartWebsockets(apolloClient.wsClient)
try {
await apolloClient.resetStore()
} catch (e) {
// eslint-disable-next-line no-console
console.log('%cError on cache reset (login)', 'color: orange;', e.message)
}
}
// Manually call this when user log out
export async function onLogout (apolloClient) {
localStorage.removeItem(AUTH_TOKEN)
if (apolloClient.wsClient) restartWebsockets(apolloClient.wsClient)
try {
await apolloClient.resetStore()
} catch (e) {
// eslint-disable-next-line no-console
console.log('%cError on cache reset (logout)', 'color: orange;', e.message)
}
}
I have what I would previously use for authentication via the header here:
const authMiddleware = new ApolloLink((operation, forward) => {
// add the authorization to the headers
const token = localStorage.getItem(AUTH_TOKEN)
operation.setContext({
headers: {
authorization: token ? `Bearer ${token}` : null
}
})
return forward(operation)
})
It seems like when I dig a bit deeper into some of the imported objects from the vue-apollo package there is something like this already built in in the createApolloClient object it has this property:
authLink = setContext(function (_, _ref2) {
var headers = _ref2.headers;
return {
headers: _objectSpread({}, headers, {
authorization: getAuth(tokenName)
})
};
});
Does this mean I can simply destructure the property off the createApolloClient object? Any help or tips much appreciated.
Take a look at vue-cli-plugin-apollo
You can pass a link: authLink and\or getAuth:()=>{return "something"} in const defaultOptions = { ... } in /vue-apollo.js.
Or in main.js when you call createProvider
new Vue({
// router, store
apolloProvider: createProvider({
link: authLink,
getAuth: AUTH_TOKEN => localStorage.getItem(AUTH_TOKEN)
}),
// ...
})
using both if you adding header in authLink, getAuth is probably redundant.
if you plan to use more than one link, there is apollo-link package link: ApolloLink.from([ ... ])

Categories

Resources