Skip to content

Commit

Permalink
feat: Extract StaticParserLoader and remove Http. Fixes (#64)
Browse files Browse the repository at this point in the history
  • Loading branch information
meeroslav committed Aug 24, 2017
1 parent 4cd3fb6 commit 8fdb355
Show file tree
Hide file tree
Showing 7 changed files with 61 additions and 134 deletions.
2 changes: 1 addition & 1 deletion LICENSE
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
Copyright (c) 2016 Greentube
Copyright (c) 2017 Greentube

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

Expand Down
20 changes: 14 additions & 6 deletions MIGRATION_GUIDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,24 @@ This guide is provided to make the transition as painless as possible.

Steps to migrate your code are:
- update the npm packages
- install new npm packages
- update the module import

Here is a detailed list of the changes that you need to make:

1. Update in your package.json `localize-router` to the latest 1.x version ([check the current release here](https://github.com/Greentube/localize-router/releases)).

2. Run `npm update` to update your packages.
2. If you were using `StaticParserLoader` you need to install [LocalizeRouterHttpLoader](https://github.com/Greentube/localize-router-http-loader):

```ts
npm install --save localize-router-http-loader
```

3. Run `npm update` to update your existing packages.

In some cases your local `node_modules` might get in broken state in which case you can try running `npm cache clean` or in worst cases deleting entire node_modules folder and running `npm install` again.

3. The module initialization `forRoot` method has changed a bit. Instead of loader, it expects an object of parameters.
4. The module initialization `forRoot` method has changed a bit. Instead of loader, it expects an object of parameters.

```ts
import { Http } from '@angular/http';
Expand All @@ -37,26 +44,27 @@ In some cases your local `node_modules` might get in broken state in which case
import { Http } from '@angular/http';
import { TranslateService } from '@ngx-translate/core';
import { Location } from '@angular/common';
import { LocalizeRouterModule, LocalizeParser, StaticParserLoader, LocalizeRouterSettings } from 'localize-router';
import { LocalizeRouterModule, LocalizeParser, LocalizeRouterSettings } from 'localize-router';
import { LocalizeRouterHttpLoader } from 'localize-router-http-loader';
LocalizeRouterModule.forRoot(routes, {
parser: {
provide: LocalizeParser,
useFactory: (translate, location, settings, http) =>
new StaticParserLoader(translate, location, settings, http, 'your/path/to/config.json'),
new LocalizeRouterHttpLoader(translate, location, settings, http, 'your/path/to/config.json'),
deps: [TranslateService, Location, LocalizeRouterSettings, Http]
}
})
```

You can now also provide additional settings regarding url prefixes and default language cache mechanisms:
5. You can now also provide additional settings to additionally configure the way `LocalizeRouter` loads and parses the routes:

```ts
LocalizeRouterModule.forRoot(routes, {
parser: {
provide: LocalizeParser,
useFactory: (translate, location, settings, http) =>
new StaticParserLoader(translate, location, settings, http, 'your/path/to/config.json'),
new LocalizeRouterHttpLoader(translate, location, settings, http, 'your/path/to/config.json'),
deps: [TranslateService, Location, LocalizeRouterSettings, Http]
},
useCachedLang: { provide: USE_CACHED_LANG, useValue: booleanValue },
Expand Down
89 changes: 34 additions & 55 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,7 @@ Demo project can be found [here](https://github.com/meeroslav/localize-router-ex
- [Installation](#installation)
- [Usage](#usage)
- [Initialize module](#initialize-module)
- [Static initialization](#static-initialization)
- [JSON config file](#json-config-file)
- [Http loader](#http-loader)
- [Initialization config](#initialization-config)
- [Manual initialization](#manual-initialization)
- [Server side initialization](#server-side-initialization)
Expand Down Expand Up @@ -46,43 +45,43 @@ In order to use `localize-router` you must initialize it with following informat
### Initialize module
Module can be initialized either using static file or manually by passing necessary values.

#### Static initialization
#### Http loader

In order to use Http loader for config files, you must include `localize-router-http-loader` package and use its `LocalizeRouterHttpLoader`.

```ts
import {BrowserModule} from "@angular/platform-browser";
import {NgModule} from '@angular/core';
import {HttpModule} from '@angular/http';
import {TranslateModule} from '@ngx-translate/core';
import {LocalizeRouterModule} from 'localize-router/localize-router';
import {LocalizeRouterModule} from 'localize-router';
import {LocalizeRouterHttpLoader} from 'localize-router-http-loader';
import {RouterModule} from '@angular/router';

import {routes} from './app.routes';

@NgModule({
imports: [
BrowserModule,
HttpModule,
TranslateModule.forRoot(),
LocalizeRouterModule.forRoot(routes),
RouterModule.forRoot(routes)
],
bootstrap: [AppComponent]
})
export class AppModule { }
```

Static file's default path is `assets/locales.json`. You can override the path by calling `StaticParserLoader` on you own:
```ts
LocalizeRouterModule.forRoot(routes, {
parser: {
imports: [
BrowserModule,
HttpModule,
TranslateModule.forRoot(),
LocalizeRouterModule.forRoot(routes, {
parser: {
provide: LocalizeParser,
useFactory: (translate, location, settings, http) =>
new StaticParserLoader(translate, location, settings, http, 'your/path/to/config.json'),
new LocalizeRouterHttpLoader(translate, location, settings, http),
deps: [TranslateService, Location, LocalizeRouterSettings, Http]
}
}
}),
RouterModule.forRoot(routes)
],
bootstrap: [AppComponent]
})

export class AppModule { }
```

More details are available on [localize-router-http-loader](https://github.com/Greentube/localize-router-http-loader).

If you are using child modules or routes you need to initialize them with `forChild` command:
```ts
@NgModule({
Expand All @@ -96,41 +95,22 @@ If you are using child modules or routes you need to initialize them with `forCh
export class ChildModule { }
```

#### JSON config file
JSON config file has following structure:
```
{
"locales": ["en", "de", ...],
"prefix": "MY_PREFIX"
}
```

```ts
interface ILocalizeRouterParserConfig {
locales: Array<string>;
prefix?: string;
}
```

Prefix field is not mandatory and default value is empty string.

#### Initialization config
Apart from providing routes which are mandatory, and parser loader you can provide additional configuration for more granular setting of `localize router`. More information at [LocalizeRouterConfig](#localizerouterconfig).


#### Manual initialization
With manual initialization you need to provide information directly:
```ts
LocalizeRouterModule.forRoot(routes, {
parser: {
provide: LocalizeParser,
useFactory: (translate, location, settigns) =>
new ManualParserLoader(translate, location, settings, ['en','de',...], 'YOUR_PREFIX'),
deps: [TranslateService, Location, LocalizeRouterSettings]
}
})

```
With manual initialization you need to provide information directly:
```ts
LocalizeRouterModule.forRoot(routes, {
parser: {
provide: LocalizeParser,
useFactory: (translate, location, settigns) =>
new ManualParserLoader(translate, location, settings, ['en','de',...], 'YOUR_PREFIX'),
deps: [TranslateService, Location, LocalizeRouterSettings]
}
})
```

#### Server side initialization
In order to use server side initialization in isomorphic/universal projects you need to create loader similar to this:
Expand All @@ -153,7 +133,6 @@ export class LocalizeUniversalLoader extends LocalizeParser {
export function localizeLoaderFactory(translate: TranslateService, location: Location, settings: LocalizeRouterSettings) {
return new LocalizeUniversalLoader(translate, location, settings);
}

```

Don't forget to create similar loader for `ngx-translate` as well:
Expand Down Expand Up @@ -217,7 +196,7 @@ Make sure you therefore place most common language (e.g. 'en') as a first string

Sometimes you might have a need to have certain routes excluded from the localization process e.g. login page, registration page etc. This is possible by setting flag `skipRouteLocalization` on route's data object.

```typescript
```ts
let routes = [
// this route gets localized
{ path: 'home', component: HomeComponent },
Expand Down
4 changes: 2 additions & 2 deletions demo/cli/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@
"@ngx-translate/core": "^7.0.0",
"@ngx-translate/http-loader": "^0.1.0",
"core-js": "^2.4.1",
"localize-router": "1.0.0-alpha.1",
"localize-router-http-loader": "0.0.1",
"localize-router": "1.0.0-alpha.3",
"localize-router-http-loader": "0.0.3",
"rxjs": "^5.1.0",
"zone.js": "^0.8.4"
},
Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "localize-router",
"version": "1.0.0-alpha.2",
"version": "1.0.0-alpha.3",
"description": "An implementation of routes localization for Angular 2",
"scripts": {
"test": "karma start",
Expand Down Expand Up @@ -36,7 +36,7 @@
"@angular/http": ">=2.0.0",
"@angular/router": ">=3.0.0",
"rxjs": "^5.0.0",
"@ngx-translate/core": "^6.0.0"
"@ngx-translate/core": ">=6.0.0"
},
"devDependencies": {
"@angular/animations": "~4.3.3",
Expand Down
27 changes: 5 additions & 22 deletions src/localize-router.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,32 +2,19 @@ import {
NgModule, ModuleWithProviders, APP_INITIALIZER, Optional, SkipSelf,
Injectable, Injector
} from '@angular/core';
import { HttpModule, Http } from '@angular/http';
import { LocalizeRouterService } from './localize-router.service';
import { LocalizeParser, StaticParserLoader } from './localize-router.parser';
import { DummyLocalizeParser, LocalizeParser } from './localize-router.parser';
import { RouterModule, Routes } from '@angular/router';
import { LocalizeRouterPipe } from './localize-router.pipe';
import { TranslateModule, TranslateService } from '@ngx-translate/core';
import { Location, CommonModule } from '@angular/common';
import { TranslateModule } from '@ngx-translate/core';
import { CommonModule } from '@angular/common';
import {
ALWAYS_SET_PREFIX,
CACHE_MECHANISM, CACHE_NAME, DEFAULT_LANG_FUNCTION, LOCALIZE_ROUTER_FORROOT_GUARD, LocalizeRouterConfig, LocalizeRouterSettings,
RAW_ROUTES,
USE_CACHED_LANG
} from './localize-router.config';

/**
* Helper function for loading external parser
* @param translate
* @param location
* @param settings
* @param http
* @returns {StaticParserLoader}
*/
export function localizeLoaderFactory(translate: TranslateService, location: Location, settings: LocalizeRouterSettings, http: Http) {
return new StaticParserLoader(translate, location, settings, http);
}

@Injectable()
export class ParserInitializer {
parser: LocalizeParser;
Expand Down Expand Up @@ -76,7 +63,7 @@ export function getAppInitializer(p: ParserInitializer, parser: LocalizeParser,
}

@NgModule({
imports: [HttpModule, CommonModule, RouterModule, TranslateModule],
imports: [CommonModule, RouterModule, TranslateModule],
declarations: [LocalizeRouterPipe],
exports: [LocalizeRouterPipe]
})
Expand All @@ -97,11 +84,7 @@ export class LocalizeRouterModule {
{ provide: CACHE_MECHANISM, useValue: config.cacheMechanism },
{ provide: DEFAULT_LANG_FUNCTION, useValue: config.defaultLangFunction },
LocalizeRouterSettings,
config.parser || {
provide: LocalizeParser,
useFactory: localizeLoaderFactory,
deps: [TranslateService, Location, LocalizeRouterSettings, Http]
},
config.parser || { provide: LocalizeParser, useClass: DummyLocalizeParser },
{
provide: RAW_ROUTES,
multi: true,
Expand Down
49 changes: 3 additions & 46 deletions src/localize-router.parser.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Routes, Route } from '@angular/router';
import { TranslateService } from '@ngx-translate/core';
import { Observable } from 'rxjs/Observable';
Expand All @@ -12,14 +11,6 @@ import { CacheMechanism, LocalizeRouterSettings } from './localize-router.config

const COOKIE_EXPIRY = 30; // 1 month

/**
* Config interface
*/
export interface ILocalizeRouterParserConfig {
locales: Array<string>;
prefix?: string;
}

/**
* Abstract class for parsing localization
*/
Expand Down Expand Up @@ -64,7 +55,7 @@ export abstract class LocalizeParser {

this.routes = routes;

if (!this.locales.length) {
if (!this.locales || !this.locales.length) {
return Promise.resolve();
}
/** detect current language */
Expand Down Expand Up @@ -396,44 +387,10 @@ export class ManualParserLoader extends LocalizeParser {
}
}

/**
* Load configuration from server
*/
export class StaticParserLoader extends LocalizeParser {
private _dataLoaded: boolean;

/**
* CTOR
* @param translate
* @param location
* @param settings
* @param http
* @param path
*/
constructor(translate: TranslateService, location: Location, settings: LocalizeRouterSettings, private http: Http, private path: string = 'assets/locales.json') {
super(translate, location, settings);
this._dataLoaded = false;
}

/**
* Initialize or append routes
* @param routes
* @returns {Promise<any>}
*/
export class DummyLocalizeParser extends LocalizeParser {
load(routes: Routes): Promise<any> {
return new Promise((resolve: any) => {
if (this._dataLoaded) {
this.init(routes).then(resolve);
} else {
this.http.get(`${this.path}`)
.map((res: Response) => res.json())
.subscribe((data: ILocalizeRouterParserConfig) => {
this._dataLoaded = true;
this.locales = data.locales;
this.prefix = data.prefix || '';
this.init(routes).then(resolve);
});
}
this.init(routes).then(resolve);
});
}
}

0 comments on commit 8fdb355

Please sign in to comment.