├── src ├── assets │ └── .gitkeep ├── app │ ├── app.component.scss │ ├── product-listing │ │ ├── actions │ │ │ ├── actions.component.scss │ │ │ ├── actions.component.html │ │ │ ├── actions.component.spec.ts │ │ │ └── actions.component.ts │ │ ├── .DS_Store │ │ ├── product-listing │ │ │ ├── product-listing.component.scss │ │ │ ├── product-listing.component.spec.ts │ │ │ ├── product-listing.component.html │ │ │ └── product-listing.component.ts │ │ ├── filter │ │ │ ├── filter.component.scss │ │ │ ├── filter.component.spec.ts │ │ │ ├── filter.component.html │ │ │ └── filter.component.ts │ │ ├── product-listing.module.ts │ │ └── _pipes │ │ │ └── custom-sort.pipe.ts │ ├── core │ │ ├── _guards │ │ │ └── module-import-guards.ts │ │ ├── core.module.ts │ │ ├── _interceptors │ │ │ └── cosmic.interceptor.ts │ │ └── _services │ │ │ ├── user.service.ts │ │ │ └── cosmic.service.ts │ ├── app.component.html │ ├── app-routing.module.ts │ ├── app.component.ts │ ├── app.module.ts │ └── app.component.spec.ts ├── favicon.ico ├── tsconfig.app.json ├── styles.scss ├── environments │ ├── environment.prod.ts │ └── environment.ts ├── models │ ├── category.ts │ ├── price-filter.ts │ ├── product.ts │ └── user.ts ├── tsconfig.spec.json ├── index.html ├── tslint.json ├── main.ts ├── browserslist ├── test.ts ├── karma.conf.js └── polyfills.ts ├── e2e ├── tsconfig.e2e.json ├── src │ ├── app.po.ts │ └── app.e2e-spec.ts └── protractor.conf.js ├── .editorconfig ├── prettier.config.js ├── server.js ├── tsconfig.json ├── .gitignore ├── set-env.ts ├── package.json ├── README.md ├── tslint.json └── angular.json /src/assets/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/app/app.component.scss: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/app/product-listing/actions/actions.component.scss: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cosmicjs/cosmic-commerce-filters/develop/src/favicon.ico -------------------------------------------------------------------------------- /src/app/product-listing/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cosmicjs/cosmic-commerce-filters/develop/src/app/product-listing/.DS_Store -------------------------------------------------------------------------------- /src/app/product-listing/product-listing/product-listing.component.scss: -------------------------------------------------------------------------------- 1 | .columns { 2 | flex-wrap: wrap; 3 | } 4 | 5 | .product-tile { 6 | margin-bottom: 1.5rem; 7 | } 8 | -------------------------------------------------------------------------------- /src/tsconfig.app.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "../out-tsc/app", 5 | "types": [] 6 | }, 7 | "exclude": [ 8 | "test.ts", 9 | "**/*.spec.ts" 10 | ] 11 | } 12 | -------------------------------------------------------------------------------- /src/styles.scss: -------------------------------------------------------------------------------- 1 | // Import Bulma 2 | @import "../node_modules/bulma/bulma.sass"; 3 | 4 | // Import Font Awesome 5 | @import "../node_modules/font-awesome/css/font-awesome.min.css"; 6 | 7 | // Import Toastr 8 | @import '~ngx-toastr/toastr.css'; 9 | -------------------------------------------------------------------------------- /src/environments/environment.prod.ts: -------------------------------------------------------------------------------- 1 | export const environment = { 2 | production: true, 3 | read_key: '##COSMIC_READ_KEY##', 4 | write_key: '##COSMIC_WRITE_KEY##', 5 | bucket_slug: 'cosmic-customization', 6 | URL: 'https://api.cosmicjs.com/v1/' 7 | }; 8 | -------------------------------------------------------------------------------- /src/app/core/_guards/module-import-guards.ts: -------------------------------------------------------------------------------- 1 | export function throwIfAlreadyLoaded(parentModule: any, moduleName: string) { 2 | if (parentModule) { 3 | throw new Error(`${moduleName} has already been loaded. Import Core modules in the AppModule only.`); 4 | } 5 | } 6 | -------------------------------------------------------------------------------- /e2e/tsconfig.e2e.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "../out-tsc/app", 5 | "module": "commonjs", 6 | "target": "es5", 7 | "types": [ 8 | "jasmine", 9 | "jasminewd2", 10 | "node" 11 | ] 12 | } 13 | } -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | # Editor configuration, see https://editorconfig.org 2 | root = true 3 | 4 | [*] 5 | charset = utf-8 6 | indent_style = space 7 | indent_size = 2 8 | insert_final_newline = true 9 | trim_trailing_whitespace = true 10 | 11 | [*.md] 12 | max_line_length = off 13 | trim_trailing_whitespace = false 14 | -------------------------------------------------------------------------------- /e2e/src/app.po.ts: -------------------------------------------------------------------------------- 1 | import { browser, by, element } from 'protractor'; 2 | 3 | export class AppPage { 4 | navigateTo() { 5 | return browser.get(browser.baseUrl) as Promise; 6 | } 7 | 8 | getTitleText() { 9 | return element(by.css('app-root h1')).getText() as Promise; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /prettier.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | printWidth: 140, 3 | tabWidth: 2, 4 | useTabs: false, 5 | semi: true, 6 | singleQuote: true, 7 | trailingComma: "none", // other options `es5` or `all` 8 | bracketSpacing: true, 9 | arrowParens: "avoid", // other option 'always' 10 | parser: "typescript" 11 | }; 12 | -------------------------------------------------------------------------------- /server.js: -------------------------------------------------------------------------------- 1 | // server.js 2 | const express = require("express"); 3 | const app = express(); 4 | // Run the app by serving the static files 5 | // in the dist directory 6 | app.use(express.static(__dirname + "/dist")); 7 | // Start the app by listening on the default 8 | // Heroku port 9 | app.listen(process.env.PORT || 8080); 10 | -------------------------------------------------------------------------------- /src/models/category.ts: -------------------------------------------------------------------------------- 1 | export class Category { 2 | _id: string; 3 | slug: string; 4 | title: string; 5 | isRoot: boolean; 6 | 7 | constructor(obj) { 8 | this._id = obj._id; 9 | this.slug = obj.slug; 10 | this.title = obj.title; 11 | this.isRoot = obj.metadata ? obj.metadata.root : false; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/tsconfig.spec.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "../out-tsc/spec", 5 | "types": [ 6 | "jasmine", 7 | "node" 8 | ] 9 | }, 10 | "files": [ 11 | "test.ts", 12 | "polyfills.ts" 13 | ], 14 | "include": [ 15 | "**/*.spec.ts", 16 | "**/*.d.ts" 17 | ] 18 | } 19 | -------------------------------------------------------------------------------- /src/models/price-filter.ts: -------------------------------------------------------------------------------- 1 | export class PriceFilter { 2 | _id: string; 3 | slug: string; 4 | title: string; 5 | max: number; 6 | min: number; 7 | 8 | constructor(obj) { 9 | this._id = obj._id; 10 | this.slug = obj.slug; 11 | this.title = obj.title; 12 | this.max = obj.metadata.max; 13 | this.min = obj.metadata.min; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CosmicCustomization 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /src/app/app.component.html: -------------------------------------------------------------------------------- 1 | 2 |
3 |
4 |

{{ title }}: buy what you really like

5 |
6 |
7 | 8 |
9 |
10 | 11 |
12 |
13 | 14 | -------------------------------------------------------------------------------- /src/tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tslint.json", 3 | "rules": { 4 | "directive-selector": [ 5 | true, 6 | "attribute", 7 | "app", 8 | "camelCase" 9 | ], 10 | "component-selector": [ 11 | true, 12 | "element", 13 | "app", 14 | "kebab-case" 15 | ] 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/main.ts: -------------------------------------------------------------------------------- 1 | import { enableProdMode } from '@angular/core'; 2 | import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; 3 | 4 | import { AppModule } from './app/app.module'; 5 | import { environment } from './environments/environment'; 6 | 7 | if (environment.production) { 8 | enableProdMode(); 9 | } 10 | 11 | platformBrowserDynamic().bootstrapModule(AppModule) 12 | .catch(err => console.error(err)); 13 | -------------------------------------------------------------------------------- /src/browserslist: -------------------------------------------------------------------------------- 1 | # This file is currently used by autoprefixer to adjust CSS to support the below specified browsers 2 | # For additional information regarding the format and rule options, please see: 3 | # https://github.com/browserslist/browserslist#queries 4 | # 5 | # For IE 9-11 support, please remove 'not' from the last line of the file and adjust as needed 6 | 7 | > 0.5% 8 | last 2 versions 9 | Firefox ESR 10 | not dead 11 | not IE 9-11 -------------------------------------------------------------------------------- /src/app/app-routing.module.ts: -------------------------------------------------------------------------------- 1 | import { NgModule } from '@angular/core'; 2 | import { Routes, RouterModule } from '@angular/router'; 3 | import { ProductListingComponent } from './product-listing/product-listing/product-listing.component'; 4 | 5 | const routes: Routes = [{ path: '', component: ProductListingComponent }]; 6 | 7 | @NgModule({ 8 | imports: [RouterModule.forRoot(routes)], 9 | exports: [RouterModule] 10 | }) 11 | export class AppRoutingModule {} 12 | -------------------------------------------------------------------------------- /src/app/core/core.module.ts: -------------------------------------------------------------------------------- 1 | import { NgModule, Optional, SkipSelf } from '@angular/core'; 2 | import { CommonModule } from '@angular/common'; 3 | import { throwIfAlreadyLoaded } from './_guards/module-import-guards'; 4 | 5 | @NgModule({ 6 | declarations: [], 7 | imports: [CommonModule] 8 | }) 9 | export class CoreModule { 10 | constructor(@Optional() @SkipSelf() parentModule: CoreModule) { 11 | throwIfAlreadyLoaded(parentModule, 'CoreModule'); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/app/product-listing/filter/filter.component.scss: -------------------------------------------------------------------------------- 1 | input:checked + span { font-weight: bold; } 2 | 3 | .color-item { 4 | display: inline-table; 5 | 6 | input { 7 | display: none; 8 | 9 | &:checked + span { 10 | border: 2px solid #000; 11 | } 12 | 13 | & + span { 14 | border: 1px solid #dbdbdb; 15 | border-radius: 4px; 16 | display: block; 17 | height: 30px; 18 | margin-right: 10px; 19 | width: 30px; 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/app/app.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { User } from '@models/user'; 3 | import { UserService } from './core/_services/user.service'; 4 | 5 | @Component({ 6 | selector: 'app-root', 7 | templateUrl: './app.component.html', 8 | styleUrls: ['./app.component.scss'] 9 | }) 10 | export class AppComponent implements OnInit { 11 | title = 'Cosmic-CommerceFilters'; 12 | 13 | constructor(private userService: UserService) {} 14 | 15 | ngOnInit() { 16 | this.userService.init(); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compileOnSave": false, 3 | "compilerOptions": { 4 | "baseUrl": "./", 5 | "outDir": "./dist/out-tsc", 6 | "sourceMap": true, 7 | "declaration": false, 8 | "module": "es2015", 9 | "moduleResolution": "node", 10 | "emitDecoratorMetadata": true, 11 | "experimentalDecorators": true, 12 | "target": "es5", 13 | "typeRoots": ["node_modules/@types"], 14 | "lib": ["es2018", "dom"], 15 | "paths": { 16 | "@environments/*": ["./src/environments/*"], 17 | "@models/*": ["./src/models/*"] 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/app/product-listing/product-listing.module.ts: -------------------------------------------------------------------------------- 1 | import { NgModule } from '@angular/core'; 2 | import { CommonModule } from '@angular/common'; 3 | import { ProductListingComponent } from './product-listing/product-listing.component'; 4 | import { ActionsComponent } from './actions/actions.component'; 5 | import { CustomSortPipe } from './_pipes/custom-sort.pipe'; 6 | import { FilterComponent } from './filter/filter.component'; 7 | 8 | @NgModule({ 9 | declarations: [ProductListingComponent, ActionsComponent, CustomSortPipe, FilterComponent], 10 | imports: [ 11 | CommonModule 12 | ] 13 | }) 14 | export class ProductListingModule { } 15 | -------------------------------------------------------------------------------- /src/app/product-listing/actions/actions.component.html: -------------------------------------------------------------------------------- 1 | 21 | -------------------------------------------------------------------------------- /src/models/product.ts: -------------------------------------------------------------------------------- 1 | import { Category } from './category'; 2 | 3 | export class Product { 4 | _id: string; 5 | slug: string; 6 | title: string; 7 | price: string; 8 | categories: Category[]; 9 | image: string; 10 | color: string; 11 | 12 | constructor(obj) { 13 | this._id = obj._id; 14 | this.slug = obj.slug; 15 | this.title = obj.title; 16 | this.price = obj.metadata.price; 17 | this.image = obj.metadata.image.url; 18 | this.color = obj.metadata.color; 19 | this.categories = []; 20 | 21 | if (obj.metadata && obj.metadata.categories) { 22 | obj.metadata.categories.map(category => this.categories.push(new Category(category))); 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/test.ts: -------------------------------------------------------------------------------- 1 | // This file is required by karma.conf.js and loads recursively all the .spec and framework files 2 | 3 | import 'zone.js/dist/zone-testing'; 4 | import { getTestBed } from '@angular/core/testing'; 5 | import { 6 | BrowserDynamicTestingModule, 7 | platformBrowserDynamicTesting 8 | } from '@angular/platform-browser-dynamic/testing'; 9 | 10 | declare const require: any; 11 | 12 | // First, initialize the Angular testing environment. 13 | getTestBed().initTestEnvironment( 14 | BrowserDynamicTestingModule, 15 | platformBrowserDynamicTesting() 16 | ); 17 | // Then we find all the tests. 18 | const context = require.context('./', true, /\.spec\.ts$/); 19 | // And load the modules. 20 | context.keys().map(context); 21 | -------------------------------------------------------------------------------- /e2e/src/app.e2e-spec.ts: -------------------------------------------------------------------------------- 1 | import { AppPage } from './app.po'; 2 | import { browser, logging } from 'protractor'; 3 | 4 | describe('workspace-project App', () => { 5 | let page: AppPage; 6 | 7 | beforeEach(() => { 8 | page = new AppPage(); 9 | }); 10 | 11 | it('should display welcome message', () => { 12 | page.navigateTo(); 13 | expect(page.getTitleText()).toEqual('Welcome to Cosmic-Customization!'); 14 | }); 15 | 16 | afterEach(async () => { 17 | // Assert that there are no errors emitted from the browser 18 | const logs = await browser.manage().logs().get(logging.Type.BROWSER); 19 | expect(logs).not.toContain(jasmine.objectContaining({ 20 | level: logging.Level.SEVERE, 21 | } as logging.Entry)); 22 | }); 23 | }); 24 | -------------------------------------------------------------------------------- /src/app/product-listing/filter/filter.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { async, ComponentFixture, TestBed } from '@angular/core/testing'; 2 | 3 | import { FilterComponent } from './filter.component'; 4 | 5 | describe('FilterComponent', () => { 6 | let component: FilterComponent; 7 | let fixture: ComponentFixture; 8 | 9 | beforeEach(async(() => { 10 | TestBed.configureTestingModule({ 11 | declarations: [ FilterComponent ] 12 | }) 13 | .compileComponents(); 14 | })); 15 | 16 | beforeEach(() => { 17 | fixture = TestBed.createComponent(FilterComponent); 18 | component = fixture.componentInstance; 19 | fixture.detectChanges(); 20 | }); 21 | 22 | it('should create', () => { 23 | expect(component).toBeTruthy(); 24 | }); 25 | }); 26 | -------------------------------------------------------------------------------- /src/app/product-listing/actions/actions.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { async, ComponentFixture, TestBed } from '@angular/core/testing'; 2 | 3 | import { ActionsComponent } from './actions.component'; 4 | 5 | describe('ActionsComponent', () => { 6 | let component: ActionsComponent; 7 | let fixture: ComponentFixture; 8 | 9 | beforeEach(async(() => { 10 | TestBed.configureTestingModule({ 11 | declarations: [ ActionsComponent ] 12 | }) 13 | .compileComponents(); 14 | })); 15 | 16 | beforeEach(() => { 17 | fixture = TestBed.createComponent(ActionsComponent); 18 | component = fixture.componentInstance; 19 | fixture.detectChanges(); 20 | }); 21 | 22 | it('should create', () => { 23 | expect(component).toBeTruthy(); 24 | }); 25 | }); 26 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # See http://help.github.com/ignore-files/ for more about ignoring files. 2 | 3 | # compiled output 4 | /dist 5 | /tmp 6 | /out-tsc 7 | # Only exists if Bazel was run 8 | /bazel-out 9 | 10 | # dependencies 11 | /node_modules 12 | 13 | # profiling files 14 | chrome-profiler-events.json 15 | speed-measure-plugin.json 16 | 17 | # IDEs and editors 18 | /.idea 19 | .project 20 | .classpath 21 | .c9/ 22 | *.launch 23 | .settings/ 24 | *.sublime-workspace 25 | 26 | # IDE - VSCode 27 | .vscode/* 28 | !.vscode/settings.json 29 | !.vscode/tasks.json 30 | !.vscode/launch.json 31 | !.vscode/extensions.json 32 | .history/* 33 | 34 | # misc 35 | /.sass-cache 36 | /connect.lock 37 | /coverage 38 | /libpeerconnection.log 39 | npm-debug.log 40 | yarn-error.log 41 | testem.log 42 | /typings 43 | 44 | # System Files 45 | .DS_Store 46 | Thumbs.db 47 | -------------------------------------------------------------------------------- /src/app/product-listing/product-listing/product-listing.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { async, ComponentFixture, TestBed } from '@angular/core/testing'; 2 | 3 | import { ProductListingComponent } from './product-listing.component'; 4 | 5 | describe('ProductListingComponent', () => { 6 | let component: ProductListingComponent; 7 | let fixture: ComponentFixture; 8 | 9 | beforeEach(async(() => { 10 | TestBed.configureTestingModule({ 11 | declarations: [ ProductListingComponent ] 12 | }) 13 | .compileComponents(); 14 | })); 15 | 16 | beforeEach(() => { 17 | fixture = TestBed.createComponent(ProductListingComponent); 18 | component = fixture.componentInstance; 19 | fixture.detectChanges(); 20 | }); 21 | 22 | it('should create', () => { 23 | expect(component).toBeTruthy(); 24 | }); 25 | }); 26 | -------------------------------------------------------------------------------- /e2e/protractor.conf.js: -------------------------------------------------------------------------------- 1 | // Protractor configuration file, see link for more information 2 | // https://github.com/angular/protractor/blob/master/lib/config.ts 3 | 4 | const { SpecReporter } = require('jasmine-spec-reporter'); 5 | 6 | exports.config = { 7 | allScriptsTimeout: 11000, 8 | specs: [ 9 | './src/**/*.e2e-spec.ts' 10 | ], 11 | capabilities: { 12 | 'browserName': 'chrome' 13 | }, 14 | directConnect: true, 15 | baseUrl: 'http://localhost:4200/', 16 | framework: 'jasmine', 17 | jasmineNodeOpts: { 18 | showColors: true, 19 | defaultTimeoutInterval: 30000, 20 | print: function() {} 21 | }, 22 | onPrepare() { 23 | require('ts-node').register({ 24 | project: require('path').join(__dirname, './tsconfig.e2e.json') 25 | }); 26 | jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } })); 27 | } 28 | }; -------------------------------------------------------------------------------- /src/environments/environment.ts: -------------------------------------------------------------------------------- 1 | // This file can be replaced during build by using the `fileReplacements` array. 2 | // `ng build --prod` replaces `environment.ts` with `environment.prod.ts`. 3 | // The list of file replacements can be found in `angular.json`. 4 | 5 | export const environment = { 6 | production: true, 7 | read_key: '##COSMIC_READ_KEY##', 8 | write_key: '##COSMIC_WRITE_KEY##', 9 | bucket_slug: 'cosmic-customization', 10 | URL: 'https://api.cosmicjs.com/v1/' 11 | }; 12 | 13 | /* 14 | * For easier debugging in development mode, you can import the following file 15 | * to ignore zone related error stack frames such as `zone.run`, `zoneDelegate.invokeTask`. 16 | * 17 | * This import should be commented out in production mode because it will have a negative impact 18 | * on performance if an error is thrown. 19 | */ 20 | // import 'zone.js/dist/zone-error'; // Included with Angular CLI. 21 | -------------------------------------------------------------------------------- /src/app/product-listing/_pipes/custom-sort.pipe.ts: -------------------------------------------------------------------------------- 1 | import { Pipe, PipeTransform } from '@angular/core'; 2 | import { Product } from '@models/product'; 3 | import { Category } from '@models/category'; 4 | 5 | @Pipe({ 6 | name: 'customSort' 7 | }) 8 | export class CustomSortPipe implements PipeTransform { 9 | transform(value: Product[], interests: JSON): Product[] { 10 | value.sort((a: Product, b: Product) => { 11 | const aWeight = this.getWeight(a.categories, interests); 12 | const bWeight = this.getWeight(b.categories, interests); 13 | 14 | if (aWeight < bWeight) { 15 | return 1; 16 | } else if (aWeight > bWeight) { 17 | return -1; 18 | } else { 19 | return 0; 20 | } 21 | }); 22 | return value; 23 | } 24 | 25 | getWeight(categories: Category[], interests: JSON) { 26 | let weight = 0; 27 | categories.forEach(category => { 28 | weight += interests[category.title] || 0; 29 | }); 30 | return weight; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/app/product-listing/product-listing/product-listing.component.html: -------------------------------------------------------------------------------- 1 |
2 |
3 | 4 |
5 |
6 | 7 |
8 | 9 |
10 | {{product.title}} 11 | ${{product.price}} 12 |
13 | 14 |
15 |
16 |
17 | There are no products that match your search, try something else. 18 |
19 |
20 |
21 | -------------------------------------------------------------------------------- /src/app/core/_interceptors/cosmic.interceptor.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { HttpInterceptor, HttpEvent, HttpHandler, HttpRequest, HttpParams } from '@angular/common/http'; 3 | import { Observable } from 'rxjs'; 4 | import { environment } from '@environments/environment'; 5 | 6 | @Injectable({ providedIn: 'root' }) 7 | export class CosmicInterceptor implements HttpInterceptor { 8 | intercept(req: HttpRequest, next: HttpHandler): Observable> { 9 | if (req.url.match(/api.cosmicjs/)) { 10 | let params = new HttpParams({ fromString: req.params.toString() }); 11 | if (req.method === 'GET') { 12 | params = params.append('read_key', environment.read_key); 13 | 14 | req = req.clone({ 15 | params: params 16 | }); 17 | } else { 18 | let payload = JSON.parse(req.body); 19 | payload.write_key = environment.write_key; 20 | 21 | req = req.clone({ 22 | body: payload 23 | }); 24 | } 25 | } 26 | return next.handle(req); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/app/product-listing/product-listing/product-listing.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { CosmicService } from 'src/app/core/_services/cosmic.service'; 3 | import { Product } from '@models/product'; 4 | import { UserService } from 'src/app/core/_services/user.service'; 5 | import { User } from '@models/user'; 6 | 7 | @Component({ 8 | selector: 'app-product-listing', 9 | templateUrl: './product-listing.component.html', 10 | styleUrls: ['./product-listing.component.scss'] 11 | }) 12 | export class ProductListingComponent implements OnInit { 13 | public productList: Product[]; 14 | public user: User; 15 | 16 | constructor(private cosmicService: CosmicService, private userService: UserService) {} 17 | 18 | ngOnInit() { 19 | this.userService.user$.subscribe(user => { 20 | this.user = user; 21 | }); 22 | } 23 | 24 | onChangeFilters(selectedFilters: string) { 25 | this.cosmicService.getProductsByQuery(selectedFilters).subscribe(products => { 26 | this.productList = products ? products : []; 27 | }); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/app/app.module.ts: -------------------------------------------------------------------------------- 1 | import { BrowserModule } from '@angular/platform-browser'; 2 | import { NgModule } from '@angular/core'; 3 | 4 | import { AppRoutingModule } from './app-routing.module'; 5 | import { AppComponent } from './app.component'; 6 | import { CoreModule } from './core/core.module'; 7 | import { HTTP_INTERCEPTORS, HttpClientModule } from '@angular/common/http'; 8 | import { CosmicInterceptor } from './core/_interceptors/cosmic.interceptor'; 9 | import { ProductListingModule } from './product-listing/product-listing.module'; 10 | import { ToastrModule } from 'ngx-toastr'; 11 | import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; 12 | 13 | @NgModule({ 14 | declarations: [AppComponent], 15 | imports: [ 16 | BrowserModule, 17 | AppRoutingModule, 18 | CoreModule, 19 | HttpClientModule, 20 | ProductListingModule, 21 | ToastrModule.forRoot(), 22 | BrowserAnimationsModule 23 | ], 24 | providers: [ 25 | { 26 | provide: HTTP_INTERCEPTORS, 27 | useClass: CosmicInterceptor, 28 | multi: true 29 | } 30 | ], 31 | bootstrap: [AppComponent] 32 | }) 33 | export class AppModule {} 34 | -------------------------------------------------------------------------------- /src/karma.conf.js: -------------------------------------------------------------------------------- 1 | // Karma configuration file, see link for more information 2 | // https://karma-runner.github.io/1.0/config/configuration-file.html 3 | 4 | module.exports = function (config) { 5 | config.set({ 6 | basePath: '', 7 | frameworks: ['jasmine', '@angular-devkit/build-angular'], 8 | plugins: [ 9 | require('karma-jasmine'), 10 | require('karma-chrome-launcher'), 11 | require('karma-jasmine-html-reporter'), 12 | require('karma-coverage-istanbul-reporter'), 13 | require('@angular-devkit/build-angular/plugins/karma') 14 | ], 15 | client: { 16 | clearContext: false // leave Jasmine Spec Runner output visible in browser 17 | }, 18 | coverageIstanbulReporter: { 19 | dir: require('path').join(__dirname, '../coverage/Cosmic-Customization'), 20 | reports: ['html', 'lcovonly', 'text-summary'], 21 | fixWebpackSourcePaths: true 22 | }, 23 | reporters: ['progress', 'kjhtml'], 24 | port: 9876, 25 | colors: true, 26 | logLevel: config.LOG_INFO, 27 | autoWatch: true, 28 | browsers: ['Chrome'], 29 | singleRun: false, 30 | restartOnFileChange: true 31 | }); 32 | }; 33 | -------------------------------------------------------------------------------- /set-env.ts: -------------------------------------------------------------------------------- 1 | const fs = require('fs'); 2 | const argv = require('yargs').argv; 3 | 4 | const environment = argv.environment ? `.${argv.environment}` : ''; 5 | 6 | const targetPath = `./src/environments/environment${environment}.ts`; 7 | 8 | fs.readFile(targetPath, 'utf8', function(readError, data) { 9 | if (readError) { 10 | return console.log(readError); 11 | } 12 | let result = data; 13 | 14 | if (process.env.COSMIC_BUCKET) { 15 | console.log('Updating COSMIC_BUCKET'); 16 | 17 | result = result.replace(/(bucket_slug:\s*')(.*)(',)/g, `$1${process.env.COSMIC_BUCKET}$3`); 18 | } 19 | if (process.env.COSMIC_READ_KEY) { 20 | console.log('Updating COSMIC_READ_KEY'); 21 | 22 | result = result.replace(/(read_key:\s*')(.*)(',)/g, `$1${process.env.COSMIC_READ_KEY}$3`); 23 | } 24 | if (process.env.COSMIC_WRITE_KEY) { 25 | console.log('Updating COSMIC_WRITE_KEY'); 26 | 27 | result = result.replace(/(write_key:\s*')(.*)(',)/g, `$1${process.env.COSMIC_WRITE_KEY}$3`); 28 | } 29 | 30 | fs.writeFile(targetPath, result, 'utf8', function(writeError) { 31 | if (writeError) { 32 | return console.log(writeError); 33 | } 34 | }); 35 | }); 36 | -------------------------------------------------------------------------------- /src/models/user.ts: -------------------------------------------------------------------------------- 1 | import { Category } from './category'; 2 | 3 | export class User { 4 | _id: string; 5 | slug: string; 6 | interests: JSON; 7 | 8 | constructor(obj?) { 9 | this._id = obj ? obj._id : ''; 10 | this.slug = obj ? obj.slug : ''; 11 | this.interests = obj ? JSON.parse(obj.metadata.interests) : {}; 12 | } 13 | 14 | postBody() { 15 | return { 16 | title: this.slug, 17 | type_slug: 'users', 18 | metafields: [ 19 | { 20 | type: 'json', 21 | title: 'interests', 22 | key: 'interests', 23 | value: JSON.stringify(this.interests) 24 | } 25 | ] 26 | }; 27 | } 28 | 29 | putBody() { 30 | return { 31 | title: this.slug, 32 | slug: this.slug, 33 | metafields: [ 34 | { 35 | type: 'json', 36 | title: 'interests', 37 | key: 'interests', 38 | value: JSON.stringify(this.interests) 39 | } 40 | ] 41 | }; 42 | } 43 | 44 | increaseInterest(category: Category, weight: number) { 45 | if (!this.interests[category.title]) { 46 | this.interests[category.title] = weight; 47 | } else { 48 | this.interests[category.title] += weight; 49 | } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/app/app.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { TestBed, async } from '@angular/core/testing'; 2 | import { RouterTestingModule } from '@angular/router/testing'; 3 | import { AppComponent } from './app.component'; 4 | 5 | describe('AppComponent', () => { 6 | beforeEach(async(() => { 7 | TestBed.configureTestingModule({ 8 | imports: [ 9 | RouterTestingModule 10 | ], 11 | declarations: [ 12 | AppComponent 13 | ], 14 | }).compileComponents(); 15 | })); 16 | 17 | it('should create the app', () => { 18 | const fixture = TestBed.createComponent(AppComponent); 19 | const app = fixture.debugElement.componentInstance; 20 | expect(app).toBeTruthy(); 21 | }); 22 | 23 | it(`should have as title 'Cosmic-Customization'`, () => { 24 | const fixture = TestBed.createComponent(AppComponent); 25 | const app = fixture.debugElement.componentInstance; 26 | expect(app.title).toEqual('Cosmic-Customization'); 27 | }); 28 | 29 | it('should render title in a h1 tag', () => { 30 | const fixture = TestBed.createComponent(AppComponent); 31 | fixture.detectChanges(); 32 | const compiled = fixture.debugElement.nativeElement; 33 | expect(compiled.querySelector('h1').textContent).toContain('Welcome to Cosmic-Customization!'); 34 | }); 35 | }); 36 | -------------------------------------------------------------------------------- /src/app/product-listing/filter/filter.component.html: -------------------------------------------------------------------------------- 1 |
    2 |
  • 3 | 7 |
  • 8 |
9 |
10 |
    11 |
  • 12 | 16 |
  • 17 |
18 |
19 |
    20 |
  • 21 | 25 |
  • 26 |
27 |
28 |
    29 |
  • 30 | 34 |
  • 35 |
36 | -------------------------------------------------------------------------------- /src/app/core/_services/user.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { User } from '@models/user'; 3 | import { CosmicService } from './cosmic.service'; 4 | import { BehaviorSubject } from 'rxjs'; 5 | 6 | @Injectable({ 7 | providedIn: 'root' 8 | }) 9 | export class UserService { 10 | private userSource = new BehaviorSubject(new User()); 11 | public user$ = this.userSource.asObservable(); 12 | 13 | constructor(private cosmicService: CosmicService) {} 14 | 15 | init() { 16 | let sessionID = localStorage.getItem('sessionID'); 17 | 18 | if (!sessionID) { 19 | const user = new User(); 20 | 21 | sessionID = Math.random() 22 | .toString(36) 23 | .substr(2, 9); 24 | 25 | localStorage.setItem('sessionID', sessionID); 26 | user.slug = sessionID; 27 | 28 | this.cosmicService.setUser(user).subscribe(user => { 29 | this.setSessionUser(user); 30 | }); 31 | } else if (!sessionStorage.getItem('user')) { 32 | this.cosmicService.getUser(sessionID).subscribe(user => this.setSessionUser(user)); 33 | } 34 | } 35 | 36 | setSessionUser(user: User) { 37 | sessionStorage.setItem('user', JSON.stringify(user)); 38 | this.userSource.next(user); 39 | } 40 | 41 | getSessionUser(): User { 42 | const user = sessionStorage.getItem('user'); 43 | 44 | if (user) { 45 | return Object.assign(new User(), JSON.parse(user)); 46 | } else { 47 | return null; 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/app/product-listing/actions/actions.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, Input, OnChanges } from '@angular/core'; 2 | import { Product } from 'src/models/product'; 3 | import { User } from '@models/user'; 4 | import { Category } from '@models/category'; 5 | import { UserService } from 'src/app/core/_services/user.service'; 6 | import { CosmicService } from 'src/app/core/_services/cosmic.service'; 7 | import { ToastrService } from 'ngx-toastr'; 8 | 9 | @Component({ 10 | selector: 'app-actions', 11 | templateUrl: './actions.component.html', 12 | styleUrls: ['./actions.component.scss'] 13 | }) 14 | export class ActionsComponent { 15 | constructor(private userService: UserService, private cosmicService: CosmicService, private toastr: ToastrService) {} 16 | 17 | @Input() product: Product; 18 | 19 | viewProduct() { 20 | this.increaseInterest(1); 21 | } 22 | 23 | addProductToCart() { 24 | this.increaseInterest(2); 25 | } 26 | 27 | buyProduct() { 28 | this.increaseInterest(3); 29 | } 30 | 31 | increaseInterest(weight: number) { 32 | const user: User = this.userService.getSessionUser(); 33 | const categories: String[] = []; 34 | this.product.categories.forEach((category: Category) => { 35 | user.increaseInterest(category, weight); 36 | categories.push(category.title); 37 | }, this); 38 | 39 | this.userService.setSessionUser(user); 40 | this.cosmicService.updateUser(user).subscribe(); 41 | 42 | this.toastr.info(`User increased interest by ${weight} points in categories ${categories.toString()}.`); 43 | window.scrollTo(0, 0); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "cosmic-commercefilters", 3 | "version": "1.0.0", 4 | "description": "Angular ecommerce website customization sample, working with headless CMS CosmicJS", 5 | "author": "Diego Perez ", 6 | "homepage": "https://imaka.github.io", 7 | "repository": { 8 | "type": "git", 9 | "url": "https://github.com/imaka/Cosmic-CommerceFilters.git" 10 | }, 11 | "license": "MIT", 12 | "scripts": { 13 | "config": "ts-node ./set-env.ts", 14 | "ng": "ng", 15 | "serve": "ng serve", 16 | "start": "node server.js", 17 | "postinstall": "npm run config && ng build", 18 | "start-prod": "npm run config -- --environment=prod && ng serve", 19 | "build": "npm run config && ng build", 20 | "compile": "npm run config && ng build", 21 | "compile-prod": "npm run config -- --environment=prod && ng build --prod --aot", 22 | "test": "ng test", 23 | "lint": "ng lint", 24 | "e2e": "ng e2e" 25 | }, 26 | "private": true, 27 | "dependencies": { 28 | "@angular/animations": "^7.2.14", 29 | "@angular/common": "~7.2.0", 30 | "@angular/compiler": "~7.2.0", 31 | "@angular/core": "~7.2.0", 32 | "@angular/forms": "~7.2.0", 33 | "@angular/platform-browser": "~7.2.0", 34 | "@angular/platform-browser-dynamic": "~7.2.0", 35 | "@angular/router": "~7.2.0", 36 | "bulma": "^0.9.0", 37 | "core-js": "^2.5.4", 38 | "express": "^4.16.4", 39 | "font-awesome": "^4.7.0", 40 | "ngx-toastr": "^10.0.2", 41 | "rxjs": "~6.3.3", 42 | "tslib": "^1.9.0", 43 | "zone.js": "~0.8.26" 44 | }, 45 | "devDependencies": { 46 | "@angular-devkit/build-angular": "~0.13.0", 47 | "@angular/cli": "~7.3.4", 48 | "@angular/compiler-cli": "~7.2.0", 49 | "@angular/language-service": "~7.2.0", 50 | "@types/jasmine": "~2.8.8", 51 | "@types/jasminewd2": "~2.0.3", 52 | "@types/node": "~8.9.4", 53 | "codelyzer": "~4.5.0", 54 | "jasmine-core": "~2.99.1", 55 | "jasmine-spec-reporter": "~4.2.1", 56 | "karma": "~4.0.0", 57 | "karma-chrome-launcher": "~2.2.0", 58 | "karma-coverage-istanbul-reporter": "~2.0.1", 59 | "karma-jasmine": "~1.1.2", 60 | "karma-jasmine-html-reporter": "^0.2.2", 61 | "prettier": "^1.19.1", 62 | "protractor": "~5.4.0", 63 | "ts-node": "~7.0.0", 64 | "tslint": "^5.11.0", 65 | "tslint-config-prettier": "^1.18.0", 66 | "typescript": "~3.2.2", 67 | "yargs": "^16.0.3" 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Ecommerce App with Personalization using Angular and Cosmic 2 | 3 | ![Ecommerce App with Personalization using Angular and Cosmic](https://imgix.cosmicjs.com/e89a72b0-1d4f-11eb-8ec3-0f4c230fe58a-cosmic-commerce-filters.png?w=2000) 4 | ### [View Demo](https://www.cosmicjs.com/apps/ecommerce-personalization-with-filters/demo) 5 | 6 | This repository showcases the use of Angular with [Cosmic](cosmicjs.com), a headless CMS service, to create a ecommerce website customization sample. More information in this article: [Build a Headless Ecommerce Product Filter with Angular and Cosmic](https://www.cosmicjs.com/articles/build-a-headless-ecommerce-product-filter-using-angular-and-cosmic) 7 | 8 | ## How to install 9 | 1. Install demo content via the Cosmic website: 10 | https://www.cosmicjs.com/apps/ecommerce-personalization-with-filters 11 | 12 | 2. Install the code locally: 13 | ``` 14 | git clone https://github.com/cosmicjs/cosmic-commerce-filters 15 | ``` 16 | 17 | 3. Once you've got your Cosmic Bucket installed, fill the data on the `environment` files as follows: 18 | ``` 19 | { 20 | production: true|false, 21 | read_key: 'COSMIC_READ_KEY', 22 | write_key: 'COSMIC_WRITE_KEY', 23 | bucket_slug: 'BUCKET_SLUG', 24 | URL: 'https://api.cosmicjs.com/v1/', 25 | presets: 'YOUR_PRESETS_OBJECT_SLUG' 26 | } 27 | ``` 28 | The `cosmic interceptor` will make sure to send the read and write keys when communicating with the CMS. 29 | 30 | You can also run the following command to quickstart the application: 31 | ``` 32 | COSMIC_BUCKET=your-bucket-slug COSMIC_WRITE_KEY=your-bucket-write-key COSMIC_READ_KEY=your-bucket-read-key npm start 33 | ``` 34 | 35 | # Angular CLI 36 | 37 | This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 7.3.4. 38 | 39 | ## Development server 40 | 41 | Run `ng serve` for a dev server. Navigate to `http://localhost:4200/`. The app will automatically reload if you change any of the source files. 42 | 43 | ## Code scaffolding 44 | 45 | Run `ng generate component component-name` to generate a new component. You can also use `ng generate directive|pipe|service|class|guard|interface|enum|module`. 46 | 47 | ## Build 48 | 49 | Run `ng build` to build the project. The build artifacts will be stored in the `dist/` directory. Use the `--prod` flag for a production build. 50 | 51 | ## Running unit tests 52 | 53 | Run `ng test` to execute the unit tests via [Karma](https://karma-runner.github.io). 54 | 55 | ## Running end-to-end tests 56 | 57 | Run `ng e2e` to execute the end-to-end tests via [Protractor](http://www.protractortest.org/). 58 | 59 | ## Further help 60 | 61 | To get more help on the Angular CLI use `ng help` or go check out the [Angular CLI README](https://github.com/angular/angular-cli/blob/master/README.md). 62 | -------------------------------------------------------------------------------- /src/polyfills.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file includes polyfills needed by Angular and is loaded before the app. 3 | * You can add your own extra polyfills to this file. 4 | * 5 | * This file is divided into 2 sections: 6 | * 1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers. 7 | * 2. Application imports. Files imported after ZoneJS that should be loaded before your main 8 | * file. 9 | * 10 | * The current setup is for so-called "evergreen" browsers; the last versions of browsers that 11 | * automatically update themselves. This includes Safari >= 10, Chrome >= 55 (including Opera), 12 | * Edge >= 13 on the desktop, and iOS 10 and Chrome on mobile. 13 | * 14 | * Learn more in https://angular.io/guide/browser-support 15 | */ 16 | 17 | /*************************************************************************************************** 18 | * BROWSER POLYFILLS 19 | */ 20 | 21 | /** IE10 and IE11 requires the following for NgClass support on SVG elements */ 22 | // import 'classlist.js'; // Run `npm install --save classlist.js`. 23 | 24 | /** 25 | * Web Animations `@angular/platform-browser/animations` 26 | * Only required if AnimationBuilder is used within the application and using IE/Edge or Safari. 27 | * Standard animation support in Angular DOES NOT require any polyfills (as of Angular 6.0). 28 | */ 29 | // import 'web-animations-js'; // Run `npm install --save web-animations-js`. 30 | 31 | /** 32 | * By default, zone.js will patch all possible macroTask and DomEvents 33 | * user can disable parts of macroTask/DomEvents patch by setting following flags 34 | * because those flags need to be set before `zone.js` being loaded, and webpack 35 | * will put import in the top of bundle, so user need to create a separate file 36 | * in this directory (for example: zone-flags.ts), and put the following flags 37 | * into that file, and then add the following code before importing zone.js. 38 | * import './zone-flags.ts'; 39 | * 40 | * The flags allowed in zone-flags.ts are listed here. 41 | * 42 | * The following flags will work for all browsers. 43 | * 44 | * (window as any).__Zone_disable_requestAnimationFrame = true; // disable patch requestAnimationFrame 45 | * (window as any).__Zone_disable_on_property = true; // disable patch onProperty such as onclick 46 | * (window as any).__zone_symbol__BLACK_LISTED_EVENTS = ['scroll', 'mousemove']; // disable patch specified eventNames 47 | * 48 | * in IE/Edge developer tools, the addEventListener will also be wrapped by zone.js 49 | * with the following flag, it will bypass `zone.js` patch for IE/Edge 50 | * 51 | * (window as any).__Zone_enable_cross_context_check = true; 52 | * 53 | */ 54 | 55 | /*************************************************************************************************** 56 | * Zone JS is required by default for Angular itself. 57 | */ 58 | import 'zone.js/dist/zone'; // Included with Angular CLI. 59 | 60 | 61 | /*************************************************************************************************** 62 | * APPLICATION IMPORTS 63 | */ 64 | -------------------------------------------------------------------------------- /tslint.json: -------------------------------------------------------------------------------- 1 | // Disabled rules conflicting with Prettier 2 | { 3 | "rulesDirectory": ["node_modules/codelyzer"], 4 | "rules": { 5 | "arrow-return-shorthand": true, 6 | "callable-types": true, 7 | "class-name": true, 8 | "comment-format": [true, "check-space"], 9 | "curly": true, 10 | "deprecation": { 11 | "severity": "warn" 12 | }, 13 | // "eofline": true, 14 | "forin": true, 15 | "import-blacklist": [true, "rxjs/Rx"], 16 | // "import-spacing": true, 17 | // "indent": [ 18 | // true, 19 | // "spaces" 20 | // ], 21 | "interface-over-type-literal": true, 22 | "label-position": true, 23 | // "max-line-length": [ 24 | // true, 25 | // 140 26 | // ], 27 | "member-access": false, 28 | "member-ordering": [ 29 | true, 30 | { 31 | "order": [ 32 | "static-field", 33 | "instance-field", 34 | "static-method", 35 | "instance-method" 36 | ] 37 | } 38 | ], 39 | "no-arg": true, 40 | "no-bitwise": true, 41 | "no-console": [true, "debug", "info", "time", "timeEnd", "trace"], 42 | "no-construct": true, 43 | "no-debugger": true, 44 | "no-duplicate-super": true, 45 | "no-empty": false, 46 | "no-empty-interface": true, 47 | "no-eval": true, 48 | "no-inferrable-types": [true, "ignore-params"], 49 | "no-misused-new": true, 50 | "no-non-null-assertion": true, 51 | "no-redundant-jsdoc": true, 52 | "no-shadowed-variable": true, 53 | "no-string-literal": false, 54 | "no-string-throw": true, 55 | "no-switch-case-fall-through": true, 56 | // "no-trailing-whitespace": true, 57 | "no-unnecessary-initializer": true, 58 | "no-unused-expression": true, 59 | "no-use-before-declare": true, 60 | "no-var-keyword": true, 61 | "object-literal-sort-keys": false, 62 | // "one-line": [ 63 | // true, 64 | // "check-open-brace", 65 | // "check-catch", 66 | // "check-else", 67 | // "check-whitespace" 68 | // ], 69 | "prefer-const": true, 70 | // "quotemark": [ 71 | // true, 72 | // "single" 73 | // ], 74 | "radix": true, 75 | // "semicolon": [ 76 | // true, 77 | // "always" 78 | // ], 79 | "triple-equals": [true, "allow-null-check"], 80 | // "typedef-whitespace": [ 81 | // true, 82 | // { 83 | // "call-signature": "nospace", 84 | // "index-signature": "nospace", 85 | // "parameter": "nospace", 86 | // "property-declaration": "nospace", 87 | // "variable-declaration": "nospace" 88 | // } 89 | // ], 90 | "unified-signatures": true, 91 | "variable-name": false, 92 | // "whitespace": [ 93 | // true, 94 | // "check-branch", 95 | // "check-decl", 96 | // "check-operator", 97 | // "check-separator", 98 | // "check-type" 99 | // ], 100 | "no-output-on-prefix": true, 101 | "use-input-property-decorator": true, 102 | "use-output-property-decorator": true, 103 | "use-host-property-decorator": true, 104 | "no-input-rename": true, 105 | "no-output-rename": true, 106 | "use-life-cycle-interface": true, 107 | "use-pipe-transform-interface": true, 108 | "component-class-suffix": true, 109 | "directive-class-suffix": true 110 | }, 111 | "extends": ["tslint-config-prettier"] 112 | } 113 | -------------------------------------------------------------------------------- /angular.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "./node_modules/@angular/cli/lib/config/schema.json", 3 | "version": 1, 4 | "newProjectRoot": "projects", 5 | "projects": { 6 | "Cosmic-Customization": { 7 | "root": "", 8 | "sourceRoot": "src", 9 | "projectType": "application", 10 | "prefix": "app", 11 | "schematics": { 12 | "@schematics/angular:component": { 13 | "style": "scss" 14 | } 15 | }, 16 | "architect": { 17 | "build": { 18 | "builder": "@angular-devkit/build-angular:browser", 19 | "options": { 20 | "outputPath": "dist", 21 | "index": "src/index.html", 22 | "main": "src/main.ts", 23 | "polyfills": "src/polyfills.ts", 24 | "tsConfig": "src/tsconfig.app.json", 25 | "assets": ["src/favicon.ico", "src/assets"], 26 | "styles": ["src/styles.scss"], 27 | "scripts": [], 28 | "es5BrowserSupport": true 29 | }, 30 | "configurations": { 31 | "production": { 32 | "fileReplacements": [ 33 | { 34 | "replace": "src/environments/environment.ts", 35 | "with": "src/environments/environment.prod.ts" 36 | } 37 | ], 38 | "optimization": true, 39 | "outputHashing": "all", 40 | "sourceMap": false, 41 | "extractCss": true, 42 | "namedChunks": false, 43 | "aot": true, 44 | "extractLicenses": true, 45 | "vendorChunk": false, 46 | "buildOptimizer": true, 47 | "budgets": [ 48 | { 49 | "type": "initial", 50 | "maximumWarning": "2mb", 51 | "maximumError": "5mb" 52 | } 53 | ] 54 | } 55 | } 56 | }, 57 | "serve": { 58 | "builder": "@angular-devkit/build-angular:dev-server", 59 | "options": { 60 | "browserTarget": "Cosmic-Customization:build" 61 | }, 62 | "configurations": { 63 | "production": { 64 | "browserTarget": "Cosmic-Customization:build:production" 65 | } 66 | } 67 | }, 68 | "extract-i18n": { 69 | "builder": "@angular-devkit/build-angular:extract-i18n", 70 | "options": { 71 | "browserTarget": "Cosmic-Customization:build" 72 | } 73 | }, 74 | "test": { 75 | "builder": "@angular-devkit/build-angular:karma", 76 | "options": { 77 | "main": "src/test.ts", 78 | "polyfills": "src/polyfills.ts", 79 | "tsConfig": "src/tsconfig.spec.json", 80 | "karmaConfig": "src/karma.conf.js", 81 | "styles": ["src/styles.scss"], 82 | "scripts": [], 83 | "assets": ["src/favicon.ico", "src/assets"] 84 | } 85 | }, 86 | "lint": { 87 | "builder": "@angular-devkit/build-angular:tslint", 88 | "options": { 89 | "tsConfig": ["src/tsconfig.app.json", "src/tsconfig.spec.json"], 90 | "exclude": ["**/node_modules/**"] 91 | } 92 | } 93 | } 94 | }, 95 | "Cosmic-Customization-e2e": { 96 | "root": "e2e/", 97 | "projectType": "application", 98 | "prefix": "", 99 | "architect": { 100 | "e2e": { 101 | "builder": "@angular-devkit/build-angular:protractor", 102 | "options": { 103 | "protractorConfig": "e2e/protractor.conf.js", 104 | "devServerTarget": "Cosmic-Customization:serve" 105 | }, 106 | "configurations": { 107 | "production": { 108 | "devServerTarget": "Cosmic-Customization:serve:production" 109 | } 110 | } 111 | }, 112 | "lint": { 113 | "builder": "@angular-devkit/build-angular:tslint", 114 | "options": { 115 | "tsConfig": "e2e/tsconfig.e2e.json", 116 | "exclude": ["**/node_modules/**"] 117 | } 118 | } 119 | } 120 | } 121 | }, 122 | "defaultProject": "Cosmic-Customization" 123 | } 124 | -------------------------------------------------------------------------------- /src/app/core/_services/cosmic.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { HttpClient } from '@angular/common/http'; 3 | import { Observable, of } from 'rxjs'; 4 | import { catchError, map, tap, shareReplay } from 'rxjs/operators'; 5 | 6 | import { environment } from '@environments/environment'; 7 | import { Category } from '@models/category'; 8 | import { User } from '@models/user'; 9 | import { Product } from '@models/product'; 10 | import { PriceFilter } from '@models/price-filter'; 11 | 12 | /** 13 | * A service to get data from CosmicJS. 14 | */ 15 | @Injectable({ 16 | providedIn: 'root' 17 | }) 18 | export class CosmicService { 19 | constructor(private http: HttpClient) {} 20 | 21 | private commonPath = environment.URL + environment.bucket_slug; 22 | private addObjectPath = this.commonPath + '/add-object'; 23 | private editObjectPath = this.commonPath + '/edit-object'; 24 | private objectTypePath = this.commonPath + '/object-type'; 25 | 26 | private singleObjectUrl = this.commonPath + '/object'; 27 | private singleObjectByIdUrl = this.commonPath + '/object-by-id'; 28 | private multipleObjectsUrl = this.commonPath + '/objects'; 29 | 30 | private productsUrl = this.objectTypePath + '/products'; 31 | private productObjectsUrl = this.multipleObjectsUrl + '?type=products'; 32 | 33 | private products$ = new Map>(); 34 | 35 | private categoriesUrl = this.objectTypePath + '/categories'; 36 | 37 | private categories$: Observable; 38 | 39 | private priceFiltersUrl = this.objectTypePath + '/pricefilters'; 40 | 41 | private priceFilters$: Observable; 42 | 43 | getUser(slug: string): Observable { 44 | const url = `${this.singleObjectUrl}/${slug}`; 45 | return this.http.get(url).pipe( 46 | tap(_ => console.log(`fetched user: ${slug}`)), 47 | map(_ => { 48 | return new User(_['object']); 49 | }), 50 | catchError(this.handleError(`getUser: ${slug}`)) 51 | ); 52 | } 53 | 54 | updateUser(user: User) { 55 | return this.http.put(this.editObjectPath, JSON.stringify(user.putBody())).pipe( 56 | map(_ => { 57 | return new User(_['object']); 58 | }), 59 | catchError(this.handleError()) 60 | ); 61 | } 62 | 63 | setUser(user: User) { 64 | return this.http.post(this.addObjectPath, JSON.stringify(user.postBody())).pipe( 65 | map(_ => { 66 | return new User(_['object']); 67 | }), 68 | catchError(this.handleError()) 69 | ); 70 | } 71 | 72 | getProducts(): Observable { 73 | if (!this.products$.get('')) { 74 | const response = this.http.get(this.productsUrl + '?sort=random').pipe( 75 | tap(_ => console.log('fetched products')), 76 | map(_ => { 77 | return _['objects'].map(element => new Product(element)); 78 | }), 79 | shareReplay(1), 80 | catchError(this.handleError('getProducts', [])) 81 | ); 82 | this.products$.set('', response); 83 | } 84 | return this.products$.get(''); 85 | } 86 | 87 | getProductsByQuery(query?: string): Observable { 88 | if (!this.products$.get(query)) { 89 | const querystring = query ? '&query=' + query : ''; 90 | 91 | const response = this.http.get(this.productObjectsUrl + '&sort=random' + querystring).pipe( 92 | tap(_ => console.log('fetched products')), 93 | map(_ => { 94 | if (_['objects']) { 95 | return _['objects'].map(element => new Product(element)); 96 | } 97 | }), 98 | shareReplay(1), 99 | catchError(this.handleError('getProducts', [])) 100 | ); 101 | this.products$.set(query, response); 102 | } 103 | return this.products$.get(query); 104 | } 105 | 106 | getCategories(): Observable { 107 | if (!this.categories$) { 108 | this.categories$ = this.http.get(this.categoriesUrl).pipe( 109 | tap(_ => console.log('fetched categories')), 110 | map(_ => { 111 | return _['objects'].map(element => new Category(element)); 112 | }), 113 | shareReplay(1), 114 | catchError(this.handleError('getCategory', [])) 115 | ); 116 | } 117 | return this.categories$; 118 | } 119 | 120 | getPriceFilters(): Observable { 121 | if (!this.priceFilters$) { 122 | this.priceFilters$ = this.http.get(this.priceFiltersUrl).pipe( 123 | tap(_ => console.log('fetched price filters')), 124 | map(_ => { 125 | return _['objects'].map(element => new PriceFilter(element)); 126 | }), 127 | shareReplay(1), 128 | catchError(this.handleError('getPriceFilters', [])) 129 | ); 130 | } 131 | return this.priceFilters$; 132 | } 133 | 134 | /** 135 | * Handle Http operation that failed. 136 | * Let the app continue. 137 | * @param operation - name of the operation that failed 138 | * @param result - optional value to return as the observable result 139 | */ 140 | private handleError(operation = 'operation', result?: T) { 141 | return (error: any): Observable => { 142 | // TODO: send the error to remote logging infrastructure 143 | console.error(error); // log to console instead 144 | 145 | // TODO: better job of transforming error for user consumption 146 | 147 | // Let the app keep running by returning an empty result. 148 | return of(result as T); 149 | }; 150 | } 151 | } 152 | -------------------------------------------------------------------------------- /src/app/product-listing/filter/filter.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, EventEmitter, OnInit, Output } from '@angular/core'; 2 | import { forEach } from '@angular/router/src/utils/collection'; 3 | import { Category } from '@models/category'; 4 | import { PriceFilter } from '@models/price-filter'; 5 | import { forkJoin } from 'rxjs'; 6 | import { CosmicService } from 'src/app/core/_services/cosmic.service'; 7 | 8 | @Component({ 9 | selector: 'app-filter', 10 | templateUrl: './filter.component.html', 11 | styleUrls: ['./filter.component.scss'] 12 | }) 13 | export class FilterComponent implements OnInit { 14 | public rootCategoryList: Map = new Map(); 15 | public categoryList: Map = new Map(); 16 | public colorList: Map = new Map(); 17 | public priceList: Map = new Map(); 18 | 19 | @Output() selectedFilters = new EventEmitter(); 20 | 21 | constructor(private cosmicService: CosmicService) {} 22 | 23 | ngOnInit() { 24 | /** */ 25 | /*hay que usar props para reducir las peticiones 26 | */ 27 | forkJoin(this.cosmicService.getCategories(), this.cosmicService.getProducts(), this.cosmicService.getPriceFilters()).subscribe( 28 | ([categories, products, priceFilters]) => { 29 | // categories 30 | categories.forEach(cat => { 31 | cat.isRoot ? this.rootCategoryList.set(cat, false) : this.categoryList.set(cat, false); 32 | }); 33 | 34 | // colors 35 | 36 | const colorSet = new Set(); // Using a Set will automatically discard repeated colors 37 | products.forEach(p => colorSet.add(p.color)); 38 | colorSet.forEach(c => { 39 | this.colorList.set(c, false); 40 | }); 41 | 42 | // prices 43 | priceFilters.forEach(pf => this.priceList.set(pf, false)); 44 | 45 | this.updateSelectedFilters(); 46 | } 47 | ); 48 | } 49 | 50 | /////////// 51 | 52 | filterRootCategory(entry?: { key: Category; value: boolean }) { 53 | this.rootCategoryList.set(entry.key, !entry.value); 54 | this.updateSelectedFilters(); 55 | } 56 | 57 | filterCategory(entry: { key: Category; value: boolean }) { 58 | this.categoryList.set(entry.key, !entry.value); 59 | this.updateSelectedFilters(); 60 | } 61 | 62 | filterColor(entry: { key: string; value: boolean }) { 63 | this.colorList.set(entry.key, !entry.value); 64 | this.updateSelectedFilters(); 65 | } 66 | 67 | filterPrice(entry: { key: PriceFilter; value: boolean }) { 68 | this.priceList.set(entry.key, !entry.value); 69 | this.updateSelectedFilters(); 70 | } 71 | 72 | /////////// 73 | 74 | setCategoryFilterSelection(collection: Map, catInSelection: string[], catNotInSelection: string[]) { 75 | const inList: string[] = []; 76 | const ninList: string[] = []; 77 | collection.forEach((selected, category) => { 78 | if (selected) { 79 | inList.push(category._id); 80 | } else { 81 | ninList.push(category._id); 82 | } 83 | }); 84 | 85 | /** 86 | * Only push elements if not all categories are either selected or unselected, 87 | * in that case we don't need filtering anything 88 | */ 89 | if (inList.length !== 0 && ninList.length !== 0) { 90 | catInSelection.push(...inList); 91 | catNotInSelection.push(...ninList); 92 | } 93 | } 94 | 95 | setColorFilterSelection(collection: Map): string[] { 96 | const inList = []; 97 | collection.forEach((value: boolean, key: string) => { 98 | if (value === true) { 99 | inList.push(key); 100 | } 101 | }); 102 | return inList; 103 | } 104 | 105 | setPriceFilterSelection(collection: Map): number[][] { 106 | const inList: number[][] = []; 107 | 108 | collection.forEach((value: boolean, key: PriceFilter) => { 109 | if (value === true) { 110 | const range = [key.min, key.max]; 111 | inList.push(range); 112 | } 113 | }); 114 | 115 | return inList; 116 | } 117 | 118 | /////////// 119 | 120 | updateSelectedFilters() { 121 | // categories 122 | const catInSelection: string[] = []; 123 | const catNotInSelection: string[] = []; 124 | 125 | this.setCategoryFilterSelection(this.categoryList, catInSelection, catNotInSelection); 126 | this.setCategoryFilterSelection(this.rootCategoryList, catInSelection, catNotInSelection); 127 | 128 | // colors 129 | 130 | const colorInSelection: string[] = this.setColorFilterSelection(this.colorList); 131 | 132 | // price 133 | const pricesInSelection: number[][] = this.setPriceFilterSelection(this.priceList); 134 | 135 | // query 136 | let jsonObj = {}; 137 | if (catInSelection.length > 0 && catNotInSelection.length > 0) { 138 | jsonObj['metadata.categories'] = { 139 | $in: catInSelection, 140 | $nin: catNotInSelection 141 | }; 142 | } 143 | if (colorInSelection.length > 0) { 144 | jsonObj['metadata.color'] = { $in: colorInSelection }; 145 | } 146 | 147 | if (pricesInSelection.length > 0) { 148 | jsonObj['$or'] = []; 149 | pricesInSelection.forEach(price => { 150 | jsonObj['$or'].push({ 151 | $and: [ 152 | { 153 | 'metadata.price': { 154 | $gte: price[0] 155 | } 156 | }, 157 | { 158 | 'metadata.price': { 159 | $lte: price[1] 160 | } 161 | } 162 | ] 163 | }); 164 | }); 165 | 166 | // Introducing "$or" means we need to combine with an "$and" for the other conditions 167 | const auxObj = { $and: [] }; 168 | 169 | auxObj.$and.push( 170 | { "'metadata.categories": jsonObj['metadata.categories'], 'metadata.color': jsonObj['metadata.color'] }, 171 | { $or: jsonObj['$or'] } 172 | ); 173 | jsonObj = auxObj; 174 | } 175 | 176 | const query = encodeURIComponent(JSON.stringify(jsonObj)); 177 | this.selectedFilters.emit(query); 178 | } 179 | } 180 | --------------------------------------------------------------------------------