How to destructuring this kind of nested Objects? - node.js

Following a request on the Microsoft Azure API translator, I get a list of languages as nested objects. I would like to recover only some values like the "language code and name, but I can't destructure the objects. If you have ideas, methods to advise me, I am really interested.
Thank you very much. Thank you very much.
I have tried to destroy nested objects but I can't.
async getAzureLanguages() {
const getLanguages: any = await new AzureLanguageApi().supportedLanguages();
let provider: string = `Microsoft`;
const languages: ILanguages[] = [{ code: ``, name: ``, providers: [``] }];
const azureLanguageKeys: any = Object.keys(getLanguages.translation);
const azureLanguageValues: any = Object.values(getLanguages.translation);
azureLanguageValues.forEach((element: { code: string; name: string }) => {
return languages.push({code: '', name: element.name, providers: [provider]})
})
// console.log('languages :', languages);
return getLanguages;
}
Here is the first result of the api request :
{"translation":{"af":{"name":"Afrikaans","nativeName":"Afrikaans","dir":"ltr"},"ar":{"name":"Arabic","nativeName":"العربية","dir":"rtl"},"bg":{"name":"Bulgarian","nativeName":"Български","dir":"ltr"},"bn":{"name":"Bangla","nativeName":"বাংলা","dir":"ltr"},"bs":{"name":"Bosnian","nativeName":"bosanski (latinica)","dir":"ltr"},"ca":{"name":"Catalan","nativeName":"Català","dir":"ltr"},"cs":{"name":"Czech","nativeName":"Čeština","dir":"ltr"},"cy":{"name":"Welsh","nativeName":"Welsh","dir":"ltr"},"da":{"name":"Danish","nativeName":"Dansk","dir":"ltr"},...
And my actual result :
languages : [ { code: '', name: '', providers: [ '' ] },
{ code: '', name: 'Afrikaans', providers: [ 'Microsoft' ] },
{ code: '', name: 'Arabic', providers: [ 'Microsoft' ] },
{ code: '', name: 'Bulgarian', providers: [ 'Microsoft' ] },
{ code: '', name: 'Bangla', providers: [ 'Microsoft' ] },
{ code: '', name: 'Bosnian', providers: [ 'Microsoft' ] },
{ code: '', name: 'Catalan', providers: [ 'Microsoft' ] },...
````
I expect to have this :
````
languages : [ { code: 'af', name: 'Afrikaans', providers: [ 'Microsoft' ] },
{ code: 'ar', name: 'Arabic', providers: [ 'Microsoft' ] },
{ code: 'bg', name: 'Bulgarian', providers: [ 'Microsoft' ] },
{ code: 'bn', name: 'Bangla', providers: [ 'Microsoft' ] },
{ code: 'bs', name: 'Bosnian', providers: [ 'Microsoft' ] },
{ code: 'ca', name: 'Catalan', providers: [ 'Microsoft' ] },...

An easier way to do what you are trying to do:
...
azureLanguageKeys.foreach(key => {
languages.push({
code: key,
name: getLanguages.translation[key].name,
providers: [provider]
});
})
Or a for..in loop:
...
for(const key in getLanguages.translation){
languages.push({
code: key,
name: getLanguages.translation[key].name,
providers: [provider]
});
}
Also, you're initializing the languages array with the blank object. Initialize it this way:
const languages: ILanguages[] = [];

Related

Nest can't resolve dependencies of the services

When I used person Service in the Organisation Service, I got the error like this:
Nest can't resolve dependencies of the PersonService (PersonModel, ?). Please make sure that the argument at index [1] is available in the OrganizationModule context.
Organization.service.ts
#Injectable()
export class OrganizationService {
constructor(
#InjectModel('Organization') private readonly organizationModel: Model<Organization>,
#Inject(forwardRef(() => UsersService))
private readonly usersService: UsersService,
private readonly mailerService: MailerService,
#Inject(forwardRef(() => PersonService))
private readonly personService: PersonService,
) {}
Organization.module.ts
#Module({
imports: [
RateLimiterModule.register({ type: 'Memory', points: 100, duration: 60 * 5, keyPrefix: 'organization' }),
MongooseModule.forFeature([
{ name: 'Organization', schema: OrganizationSchema },
{ name: 'User', schema: UserSchema },
{ name: 'Person', schema: PersonSchema },
]),
PassportModule.register({ defaultStrategy: 'jwt', session: false }),
forwardRef(() => UsersModule),
forwardRef(() => PersonModule),
],
exports: [OrganizationService],
controllers: [OrganizationController],
providers: [OrganizationService, UsersService, PersonService]
})
Person.module.ts
#Module({
imports: [
RateLimiterModule.register({ type: 'Memory', points: 100, duration: 60 * 5 }),
MongooseModule.forFeature([
{ name: 'Person', schema: PersonSchema },
{ name: 'User', schema: UserSchema },
]),
PassportModule.register({ defaultStrategy: 'jwt', session: false }),
forwardRef(() => UsersModule),
],
exports: [PersonService],
controllers: [PersonController],
providers: [PersonService, UsersService]
})
export class PersonModule {
public configure(consumer: MiddlewareConsumer) {
consumer
.apply(LoggerMiddleware)
.forRoutes(PersonController);
consumer
.apply(SiteMiddleware)
.forRoutes(PersonController);
}
}
What is the error in this code?
You shouldn't re-add dependencies to providers arrays. You already define the PersonService provider in the PersonModule, and the PersonModule properly exports that provider, so all that needs to happen is the OrganizationModule needs to have PersonModule in the imports.
By putting PersonService in the OrganizationModule's providers, Nest will try to recreate the provider in the context of the OrganiztionModule, meaning it will need access to getModelToken('Person') and UsersService as other providers in the current context.

proxy a request on docusaurus

// #ts-check
// Note: type annotations allow type checking and IDEs autocompletion
const lightCodeTheme = require('prism-react-renderer/themes/github');
const darkCodeTheme = require('prism-react-renderer/themes/dracula');
/** #type {import('#docusaurus/types').Config} */
const config = {
title: 'title',
tagline: 'tag,
url: 'some-utl',
baseUrl: '/',
onBrokenLinks: 'throw',
onBrokenMarkdownLinks: 'warn',
favicon: 'img/favicon.ico',
organizationName: 'facebook', // Usually your GitHub org/user name.
projectName: 'project', // Usually your repo name.
plugins: [
[
'docusaurus-plugin-openapi',
{
id: 'api',
path: './openapi.json',
routeBasePath: '/api',
},
],
],
presets: [
[
'docusaurus-preset-openapi',
/** #type {import('docusaurus-preset-openapi').Options} */
({
api: {
path: './openapi.json',
},
theme: {
customCss: require.resolve('./src/css/custom.css'),
},
proxy: {
'/api': {
target: 'http://localhost:3000',
},
},
}),
],
],
themeConfig:
/** #type {import('docusaurus-preset-openapi').ThemeConfig} */
({
navbar: {
title: 'title',
logo: {
alt: 'My Site Logo',
src: 'img/logo.svg',
},
items: [{ to: '/api', label: 'API', position: 'left' }],
},
prism: {
theme: lightCodeTheme,
darkTheme: darkCodeTheme,
},
}),
};
module.exports = config;
This is my code for the docusaurus config file but some how the proxy doesn't work

Change an array loaded from another component in React.js jsx

I am trying to change a hardcoded array within another JSX file.
the first file routes.js. I tried loading the array then changing it . it just changes the loaded data not the array directly from the other file. How do i write to the other JSX array from the main component.
const routes = [
{
type: "collapse",
name: "Our Mission",
key: "dashboards",
icon: <Shop size="12px" />,
collapse: [
{
name: "Ways We can Help",
key: "default",
route: "/dashboards/default",
component: Default,
},
{
name: "How It Works",
key: "automotive",
route: "/dashboards/automotive",
component: Automotive,
},
{
name: "Who We Are",
key: "smart-home",
route: "/dashboards/smart-home",
component: SmartHome,
},
],
},
{ type: "title", title: " ", key: "space1" },
{
type: "collapse",
name: "Services",
key: "services",
icon: <Shop size="12px" />,
href: "https://github.com/creativetimofficial/ct-soft-ui-dashboard-pro-material-ui/blob/main/CHANGELOG.md",
component: Default,
noCollapse: true,
},
{
type: "collapse",
name: "Products",
key: "products",
icon: <Shop size="12px" />,
href: "https://github.com/creativetimofficial/ct-soft-ui-dashboard-pro-material-ui/blob/main/CHANGELOG.md",
component: Default,
noCollapse: true,
},
];
export default routes;
code used in main jsx file. I want to be able to write to the remote array changing its values.
const handleSubmit = (event) => {
event.preventDefault();
// I want to push or filter with the code below
{
routes.length = 0;
routes.map((route) => console.log({ route }));
}
};
You can't change the array itself because it's a const. You could change it to a let and then export it like this:
EDIT
export let routes = [
{
type: "collapse",
name: "Our Mission",
key: "dashboards",
icon: <Shop size="12px" />,
collapse: [
{
name: "Ways We can Help",
key: "default",
route: "/dashboards/default",
component: Default,
},
{
name: "How It Works",
key: "automotive",
route: "/dashboards/automotive",
component: Automotive,
},
{
name: "Who We Are",
key: "smart-home",
route: "/dashboards/smart-home",
component: SmartHome,
},
],
},
{ type: "title", title: " ", key: "space1" },
{
type: "collapse",
name: "Services",
key: "services",
icon: <Shop size="12px" />,
href: "https://github.com/creativetimofficial/ct-soft-ui-dashboard-pro-material-ui/blob/main/CHANGELOG.md",
component: Default,
noCollapse: true,
},
{
type: "collapse",
name: "Products",
key: "products",
icon: <Shop size="12px" />,
href: "https://github.com/creativetimofficial/ct-soft-ui-dashboard-pro-material-ui/blob/main/CHANGELOG.md",
component: Default,
noCollapse: true,
},
];
Then to use it in another jsx component you can import it like this.
import {routes} from '../yourPathToIt/main'

How to set up my routing that "pathMatch" and childRoutingModule work?

On the left-side menu I need to have the links highlighted when the user on them. Now it works but my root path 'li' of the menu is highlighted as well.
I cannot set up a child routing Module.
left-side-menu html
<ul class='side-menu'>
<li *ngFor='let item of menu' routerLinkActive='active-side-menu-item'><a routerLink='{{ item.link }}' class="menu-item-feed">{{ item.title }}</a></li>
</ul>
app.routing.module ts
import { NgModule } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { FeedComponent } from './feed/feed.component';
const routes: Routes = [
{ path: '', pathMatch: 'full', component: FeedComponent },
{ path: 'shoes', pathMatch: 'full', component: FeedComponent },
{ path: 'coats', pathMatch: 'full', component: FeedComponent },
{ path: 'shirts', pathMatch: 'full', component: FeedComponent },
{ path: 'pants', pathMatch: 'full', component: FeedComponent },
{ path: 'item/:id', component: FeedComponent },
];
#NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
That's how I tried to implement my childRoutingModule but it throws the error in the console: core.js:15724 ERROR Error: Uncaught (in promise): TypeError: undefined is not a function
TypeError: undefined is not a function
at Array.map ()
app.routing.module
const routes: Routes = [
{ path: '', pathMatch: 'full', loadChildren: './feed/feed.module#FeedModule' }
];
feed-routing.module
import { NgModule } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { FeedComponent } from './feed.component';
const routes: Routes = [
{ path: '', pathMatch: 'full', component: FeedComponent },
{ path: 'shoes', pathMatch: 'full', component: FeedComponent },
{ path: 'coats', pathMatch: 'full', component: FeedComponent },
{ path: 'shirts', pathMatch: 'full', component: FeedComponent },
{ path: 'pants', pathMatch: 'full', component: FeedComponent },
{ path: 'item/:id', component: FeedComponent },
];
#NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class FeedRoutingModule { }
I want to have a separate routing module for each gross section on the site and I need link react to the url and indicate which module is active at the moment.
I would appreciate any other hints and best practices!
To setup feature route you have to import FeedRoutingModule into the module you want to use thoose route.
Below is my example
I have app.routing.ts (Main route)
export const routes: Routes = [
{ path: "", redirectTo: "home", pathMatch: "full" },
{ path: "home", component: HomeComponent },
//{ path: "**", redirectTo: "account", pathMatch: "full" },
//lazy load feature module
{ path: "account", loadChildren: "./account/account.module#AccountModule" },
{ path: "portal", loadChildren: "./portal/portal.module#PortalModule", canActivate: [AuthGuardService] },
{ path: "**", redirectTo: "account", pathMatch: "full" },
];
and app.module.ts
#NgModule({
declarations: [],
imports: [
RouterModule.forRoot(routes)
],
providers: [],
bootstrap: []
})
export class AppModule {}
So when I define child route in my feature module I have to done the same like app.module but using RouterModule.forChild
export const accountRoutes: Routes = [
{
path: "",
component: AccountComponent,
children: [
{ path: "login", component: LoginComponent },
{ path: "register-account", component: RegisterComponent }
]
}
];
import { NgModule } from "#angular/core";
import { CommonModule } from "#angular/common";
import { FormsModule, ReactiveFormsModule } from "#angular/forms";
import { RouterModule } from "#angular/router";
import { RegisterComponent } from "./register/register.component";
import { LoginComponent } from "./login/login.component";
import { AccountComponent } from "./account/account.component";
import { accountRoutes } from "./account.routing";
#NgModule({
declarations: [],
imports: [
RouterModule.forChild(accountRoutes) // use forChild
],
exports: [],
providers: []
})
export class AccountModule {}
Your paranet component need have tag: < router-outlet>< /router-outlet> then he knows will have a child component + route;
Here a exemple where i management childRoutes.
{
path: 'utente',
component: CenterViewComponent,
children: [
YYY_ROUTE,
XXX_ROUTE
...
]
}
Hope help u!

Mustache tamplate can run on node.js but not on Ruby

this recursive Mustache template can run on node.js, but if I run it on ruby, it gives very strange output. Why that happened and how can I fix it?
const mustache = require('mustache')
const componentTemplate = `
<span class="name">{{name}}</span>
{{#components.length}}
<ul>{{#components}}<li>{{>componentTemplate}}</li>{{/components}}</ul>
{{/components.length}}
`;
const view = {
name: 'System',
components: [
{ name: 'Display',
components: [
{ name: 'Monitor 1', components: [] },
{ name: 'Monitor 2', components: [] }
]
},
{ name: 'Processor',
components: [
{ name: 'CPU', components: [] },
{ name: 'Memory', components: [] },
],
},
{ name: 'Keyboard', components: [] },
{ name: 'Mouse', components: [] }
]
};
const partials = {
componentTemplate: componentTemplate
};
console.log(mustache.render(componentTemplate, view, partials));

Resources