├── .github └── screen.gif ├── .gitignore ├── README.md ├── client ├── .editorconfig ├── .gitignore ├── .prettierrc ├── README.md ├── angular.json ├── assets │ ├── cordova │ │ ├── config.xml │ │ └── package.json │ ├── electron │ │ ├── cpuValues.js │ │ ├── icon.ico │ │ ├── index.js │ │ ├── installerconfig.json │ │ ├── package.json │ │ └── trayIcon.js │ ├── img │ │ ├── icon.png │ │ └── splash.png │ └── toggleHamburger.js ├── browserslist ├── e2e │ ├── protractor.conf.js │ ├── src │ │ ├── app.e2e-spec.ts │ │ └── app.po.ts │ └── tsconfig.json ├── karma.conf.js ├── package-lock.json ├── package.json ├── src │ ├── app │ │ ├── app.component.html │ │ ├── app.component.ts │ │ ├── app.module.ts │ │ ├── app.routes.ts │ │ ├── core │ │ │ ├── core.module.ts │ │ │ ├── data-services │ │ │ │ ├── food-data.service.ts │ │ │ │ ├── httpWrapper.service.ts │ │ │ │ └── ingredient-data.service.ts │ │ │ ├── interceptors │ │ │ │ ├── index.ts │ │ │ │ └── standard-header.interceptor.ts │ │ │ ├── services │ │ │ │ ├── abstract-camera.service.ts │ │ │ │ ├── abstract-notification.service.ts │ │ │ │ ├── currentUser.service.ts │ │ │ │ ├── desktop-camera.service.ts │ │ │ │ ├── desktop-cpuValue.service.ts │ │ │ │ ├── desktop-notification.service.ts │ │ │ │ ├── mobile-camera.service.ts │ │ │ │ ├── mobile-notification.service.ts │ │ │ │ ├── platform-information.provider.ts │ │ │ │ ├── signalR.service.ts │ │ │ │ ├── sort.service.ts │ │ │ │ ├── storage.service.ts │ │ │ │ └── web-notification.service.ts │ │ │ └── store │ │ │ │ ├── actions │ │ │ │ ├── core.actions.ts │ │ │ │ └── index.ts │ │ │ │ ├── core-store.facade.ts │ │ │ │ ├── effects │ │ │ │ ├── core.effects.ts │ │ │ │ └── index.ts │ │ │ │ ├── reducers │ │ │ │ ├── core.reducer.ts │ │ │ │ └── index.ts │ │ │ │ └── selectors │ │ │ │ ├── core.selectors.ts │ │ │ │ └── index.ts │ │ ├── food │ │ │ ├── container │ │ │ │ ├── food-details │ │ │ │ │ ├── food-details.component.html │ │ │ │ │ └── food-details.component.ts │ │ │ │ ├── index.ts │ │ │ │ ├── ingredients │ │ │ │ │ ├── ingredients.component.css │ │ │ │ │ ├── ingredients.component.html │ │ │ │ │ ├── ingredients.component.spec.ts │ │ │ │ │ └── ingredients.component.ts │ │ │ │ └── main-food │ │ │ │ │ ├── main-food.component.html │ │ │ │ │ └── main-food.component.ts │ │ │ ├── food.module.ts │ │ │ ├── food.routes.ts │ │ │ ├── guards │ │ │ │ ├── food-is-loaded.guard.ts │ │ │ │ └── index.ts │ │ │ ├── pipes │ │ │ │ ├── filter.pipe.spec.ts │ │ │ │ └── filter.pipe.ts │ │ │ ├── presentational │ │ │ │ ├── food-form │ │ │ │ │ ├── food-form.component.html │ │ │ │ │ └── food-form.component.ts │ │ │ │ ├── food-list │ │ │ │ │ ├── food-list.component.css │ │ │ │ │ ├── food-list.component.html │ │ │ │ │ └── food-list.component.ts │ │ │ │ ├── food-picture │ │ │ │ │ ├── food-picture.component.css │ │ │ │ │ ├── food-picture.component.html │ │ │ │ │ ├── food-picture.component.spec.ts │ │ │ │ │ └── food-picture.component.ts │ │ │ │ ├── index.ts │ │ │ │ └── ingredient-list │ │ │ │ │ ├── ingredient-list.component.css │ │ │ │ │ ├── ingredient-list.component.html │ │ │ │ │ ├── ingredient-list.component.spec.ts │ │ │ │ │ └── ingredient-list.component.ts │ │ │ ├── store │ │ │ │ ├── actions │ │ │ │ │ ├── food.actions.ts │ │ │ │ │ ├── index.ts │ │ │ │ │ ├── ingredients.actions.ts │ │ │ │ │ └── signalR.actions.ts │ │ │ │ ├── effects │ │ │ │ │ ├── food.effects.ts │ │ │ │ │ ├── index.ts │ │ │ │ │ └── ingredients.effects.ts │ │ │ │ ├── food-store.facade.ts │ │ │ │ ├── reducers │ │ │ │ │ ├── food.reducer.spec.ts │ │ │ │ │ ├── food.reducer.ts │ │ │ │ │ ├── index.ts │ │ │ │ │ └── ingredient.reducer.ts │ │ │ │ └── selectors │ │ │ │ │ ├── foods.selectors.ts │ │ │ │ │ ├── index.ts │ │ │ │ │ └── ingredients.selectors.ts │ │ │ └── validators │ │ │ │ ├── isInRange.validator.ts │ │ │ │ ├── isInRangeValidator.spec.ts │ │ │ │ ├── isNumber.validator.spec.ts │ │ │ │ └── isNumber.validator.ts │ │ ├── home │ │ │ ├── home.module.ts │ │ │ ├── home.routes.ts │ │ │ ├── home │ │ │ │ ├── home.component.css │ │ │ │ ├── home.component.html │ │ │ │ ├── home.component.spec.ts │ │ │ │ └── home.component.ts │ │ │ ├── randomMeal │ │ │ │ ├── randomMeal.component.html │ │ │ │ ├── randomMeal.component.spec.ts │ │ │ │ └── randomMeal.component.ts │ │ │ ├── single-meal │ │ │ │ ├── single-meal.component.css │ │ │ │ ├── single-meal.component.html │ │ │ │ ├── single-meal.component.spec.ts │ │ │ │ └── single-meal.component.ts │ │ │ └── store │ │ │ │ ├── actions │ │ │ │ ├── home.actions.ts │ │ │ │ └── index.ts │ │ │ │ ├── effects │ │ │ │ ├── home.effects.ts │ │ │ │ └── index.ts │ │ │ │ ├── home-store.facade.ts │ │ │ │ ├── reducers │ │ │ │ ├── home.reducer.ts │ │ │ │ └── index.ts │ │ │ │ └── selectors │ │ │ │ ├── home.selectors.ts │ │ │ │ └── index.ts │ │ ├── shared │ │ │ ├── components │ │ │ │ ├── footer │ │ │ │ │ ├── eMeail-footer.component.spec.ts │ │ │ │ │ ├── eMeal-footer.component.html │ │ │ │ │ └── eMeal-footer.component.ts │ │ │ │ └── navigation │ │ │ │ │ ├── navigation.component.html │ │ │ │ │ ├── navigation.component.spec.ts │ │ │ │ │ └── navigation.component.ts │ │ │ ├── configuration │ │ │ │ ├── app.configuration.spec.ts │ │ │ │ └── app.configuration.ts │ │ │ ├── models │ │ │ │ ├── foodItem.model.ts │ │ │ │ ├── ingredient.model.ts │ │ │ │ └── model.descriptor.ts │ │ │ └── shared.module.ts │ │ └── store │ │ │ ├── index.ts │ │ │ └── reducers │ │ │ ├── index.ts │ │ │ └── router.reducer.ts │ ├── assets │ │ └── .gitkeep │ ├── cordova.js │ ├── environments │ │ ├── environment.desktop.ts │ │ ├── environment.mobile.ts │ │ ├── environment.prod.ts │ │ └── environment.ts │ ├── favicon.ico │ ├── index.html │ ├── main.ts │ ├── polyfills.ts │ ├── styles.css │ ├── test.ts │ └── testing │ │ ├── CpuValueServiceMock.ts │ │ ├── abstractCameraServiceMock.ts │ │ ├── abstractNotificationServiceMock.ts │ │ └── foodServiceMock.ts ├── tsconfig.app.json ├── tsconfig.json ├── tsconfig.spec.json └── tslint.json └── server └── ASP.NETCore ├── FoodAPICore.sln └── src └── FoodAPICore ├── .vscode └── launch.json ├── Controllers ├── FoodsController.cs └── IngredientsController.cs ├── Dtos ├── FoodCreateDto.cs ├── FoodItemDto.cs ├── FoodUpdateDto.cs ├── IngredientDto.cs ├── IngredientUpdateDto.cs └── LinkDto.cs ├── Entities ├── FoodDbContext.cs ├── FoodItem.cs └── Ingredient.cs ├── FoodAPICore.csproj ├── FoodAPICore.csproj.user ├── Helpers ├── DynamicExtensions.cs └── QueryParametersExtensions.cs ├── Hubs └── FoodHub.cs ├── MappingProfiles ├── FoodMappings.cs └── IngredientMappings.cs ├── Migrations ├── 20170418041355_MyFirst.Designer.cs ├── 20170418041355_MyFirst.cs ├── 20180902180236_latest.Designer.cs ├── 20180902180236_latest.cs └── FoodDbContextModelSnapshot.cs ├── Models └── QueryParameters.cs ├── Program.cs ├── Properties └── launchSettings.json ├── Repositories ├── Food │ └── FoodRepository.cs ├── IFoodRepository.cs ├── IIngredientRepository.cs └── Ingredient │ └── IngredientRepository.cs ├── Services ├── EnsureDatabaseDataService.cs └── IEnsureDatabaseDataService.cs ├── Startup.cs ├── appsettings.json └── web.config /.github/screen.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FabianGosebrink/ASPNETCore-Angular-Ngrx/8c697557c83d8375a1ea06ab5fdfd19348e29204/.github/screen.gif -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | server/ASP.NETCore/.vs 2 | server/ASP.NETCore/src/FoodAPICore/bin 3 | server/ASP.NETCore/src/FoodAPICore/appsettings.production.json 4 | server/ASP.NETCore/src/FoodAPICore/Properties/PublishProfiles/ 5 | /client/.dist 6 | 7 | /client/src/app/**/*.js 8 | /client/src/app/**/*.js.map 9 | /server/ASP.NETCore/src/FoodAPICore/obj 10 | /server/ASP.NETCore/src/*.log 11 | /client/.temp/ 12 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Build Status](https://travis-ci.org/FabianGosebrink/ASPNETCore-Angular-Ngrx.svg?branch=master)](https://travis-ci.org/FabianGosebrink/ASPNETCore-Angular-Ngrx) 2 | 3 | # ASP.NET Core WebAPI with SignalR & Angular Demo with NgRx store & NgRx effects, Component based design (Cross Platform) 4 | 5 |

6 | 7 | Twitter: FabianGosebrink 8 | 9 |

10 | This repository offers you a demo application implemented with the AngularCLI and an endpoint using ASP.NET Core WebAPI. 11 | 12 | The application comes with lazy loading, forms, custom validation, routing, NgRx store, NgRx effects, facade pattern etc. 13 | 14 | Server and Client are completely seperated that you can exchange the endpoint easily. 15 | 16 | ### Check the corresponding package.json for the npm commands to start the repository 17 | 18 | # Demo 19 | 20 | ![DemoGif](.github/screen.gif) 21 | 22 | You can see an Angular Demo with all the techniques combined here (running on Azure) 23 | 24 | ### Frontend 25 | 26 | [https://conference-xplatform-client.azurewebsites.net](https://conference-xplatform-client.azurewebsites.net/) 27 | 28 | ### Backend 29 | 30 | [https://conference-xplatform-server.azurewebsites.net](https://conference-xplatform-server.azurewebsites.net/) 31 | 32 | ## Author 33 | 34 | 👤 **Fabian Gosebrink** 35 | 36 | - Twitter: [@FabianGosebrink](https://twitter.com/FabianGosebrink) 37 | - Github: [@FabianGosebrink](https://github.com/FabianGosebrink) 38 | 39 | ## Prerequisites 40 | 41 | - [Android SDK](https://developer.android.com/sdk/index.html) 42 | - [Windows 10 SDK](https://dev.windows.com/en-us/downloads/windows-10-sdk) 43 | - Download and install [ImageMagick](http://www.imagemagick.org/script/download.php) (base toolkit for image processing, used here for splash screen and icon generation) 44 | 45 | ## Angular Client 46 | 47 | This client is implemented with Angular. You can start the application by running 48 | 49 | `npm install` 50 | 51 | and 52 | 53 | `npm start` 54 | 55 | the application starts and runs in your default browser. 56 | 57 | ### Build Web 58 | 59 | use the `npm run build-web` command and see the `.dist/web` folder. 60 | 61 | ### Build Mobile 62 | 63 | use the `npm run build-mobile` command and see the `.dist/mobile` folder. 64 | 65 | ### Build Desktop 66 | 67 | use the `npm run build-desktop` command and see the `.dist/desktop` folder. 68 | 69 | ### Build Web, Desktop and Mobile 70 | 71 | `npm run build-all` 72 | 73 | for building Web, Desktop (Windows and Linux) and Apps for Android in the `.dist` folder. 74 | 75 | ## Show your support 76 | 77 | Give a ⭐️ if this project helped you! 78 | -------------------------------------------------------------------------------- /client/.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 | -------------------------------------------------------------------------------- /client/.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 | -------------------------------------------------------------------------------- /client/.prettierrc: -------------------------------------------------------------------------------- 1 | { "singleQuote": true } 2 | -------------------------------------------------------------------------------- /client/README.md: -------------------------------------------------------------------------------- 1 | # Emeal 2 | 3 | This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 9.0.1. 4 | 5 | ## Development server 6 | 7 | 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. 8 | 9 | ## Code scaffolding 10 | 11 | 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`. 12 | 13 | ## Build 14 | 15 | 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. 16 | 17 | ## Running unit tests 18 | 19 | Run `ng test` to execute the unit tests via [Karma](https://karma-runner.github.io). 20 | 21 | ## Running end-to-end tests 22 | 23 | Run `ng e2e` to execute the end-to-end tests via [Protractor](http://www.protractortest.org/). 24 | 25 | ## Further help 26 | 27 | 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). 28 | -------------------------------------------------------------------------------- /client/angular.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "./node_modules/@angular/cli/lib/config/schema.json", 3 | "version": 1, 4 | "newProjectRoot": "projects", 5 | "projects": { 6 | "emeal": { 7 | "projectType": "application", 8 | "schematics": {}, 9 | "root": "", 10 | "sourceRoot": "src", 11 | "prefix": "app", 12 | "architect": { 13 | "build": { 14 | "builder": "@angular-devkit/build-angular:browser", 15 | "options": { 16 | "outputPath": "dist/emeal", 17 | "index": "src/index.html", 18 | "main": "src/main.ts", 19 | "polyfills": "src/polyfills.ts", 20 | "tsConfig": "tsconfig.app.json", 21 | "aot": true, 22 | "assets": [ 23 | "src/favicon.ico", 24 | "src/assets", 25 | "src/manifest.json", 26 | "src/cordova.js" 27 | ], 28 | "styles": [ 29 | "node_modules/bootstrap/dist/css/bootstrap.css", 30 | "node_modules/font-awesome/css/font-awesome.css", 31 | "node_modules/ngx-toastr/toastr.css", 32 | "src/styles.css" 33 | ], 34 | "scripts": ["node_modules/bootstrap/dist/js/bootstrap.js"] 35 | }, 36 | "configurations": { 37 | "production": { 38 | "fileReplacements": [ 39 | { 40 | "replace": "src/environments/environment.ts", 41 | "with": "src/environments/environment.prod.ts" 42 | } 43 | ], 44 | "optimization": true, 45 | "outputHashing": "all", 46 | "sourceMap": false, 47 | "extractCss": true, 48 | "namedChunks": false, 49 | "extractLicenses": true, 50 | "vendorChunk": false, 51 | "buildOptimizer": true, 52 | "budgets": [ 53 | { 54 | "type": "initial", 55 | "maximumWarning": "2mb", 56 | "maximumError": "5mb" 57 | }, 58 | { 59 | "type": "anyComponentStyle", 60 | "maximumWarning": "6kb", 61 | "maximumError": "10kb" 62 | } 63 | ] 64 | }, 65 | "mobile": { 66 | "fileReplacements": [ 67 | { 68 | "replace": "src/environments/environment.ts", 69 | "with": "src/environments/environment.mobile.ts" 70 | } 71 | ], 72 | "optimization": true, 73 | "outputHashing": "all", 74 | "sourceMap": false, 75 | "extractCss": true, 76 | "namedChunks": false, 77 | "extractLicenses": true, 78 | "vendorChunk": false, 79 | "buildOptimizer": true 80 | }, 81 | "desktop": { 82 | "fileReplacements": [ 83 | { 84 | "replace": "src/environments/environment.ts", 85 | "with": "src/environments/environment.desktop.ts" 86 | } 87 | ], 88 | "optimization": true, 89 | "outputHashing": "all", 90 | "sourceMap": false, 91 | "extractCss": true, 92 | "namedChunks": false, 93 | "extractLicenses": true, 94 | "vendorChunk": false, 95 | "buildOptimizer": true 96 | } 97 | } 98 | }, 99 | "serve": { 100 | "builder": "@angular-devkit/build-angular:dev-server", 101 | "options": { 102 | "browserTarget": "emeal:build" 103 | }, 104 | "configurations": { 105 | "production": { 106 | "browserTarget": "emeal:build:production" 107 | } 108 | } 109 | }, 110 | "extract-i18n": { 111 | "builder": "@angular-devkit/build-angular:extract-i18n", 112 | "options": { 113 | "browserTarget": "emeal:build" 114 | } 115 | }, 116 | "test": { 117 | "builder": "@angular-devkit/build-angular:karma", 118 | "options": { 119 | "main": "src/test.ts", 120 | "polyfills": "src/polyfills.ts", 121 | "tsConfig": "tsconfig.spec.json", 122 | "karmaConfig": "karma.conf.js", 123 | "assets": ["src/favicon.ico", "src/assets"], 124 | "styles": ["src/styles.css"], 125 | "scripts": [] 126 | } 127 | }, 128 | "lint": { 129 | "builder": "@angular-devkit/build-angular:tslint", 130 | "options": { 131 | "tsConfig": [ 132 | "tsconfig.app.json", 133 | "tsconfig.spec.json", 134 | "e2e/tsconfig.json" 135 | ], 136 | "exclude": ["**/node_modules/**"] 137 | } 138 | }, 139 | "e2e": { 140 | "builder": "@angular-devkit/build-angular:protractor", 141 | "options": { 142 | "protractorConfig": "e2e/protractor.conf.js", 143 | "devServerTarget": "emeal:serve" 144 | }, 145 | "configurations": { 146 | "production": { 147 | "devServerTarget": "emeal:serve:production" 148 | } 149 | } 150 | } 151 | } 152 | } 153 | }, 154 | "defaultProject": "emeal", 155 | "cli": { 156 | "analytics": false 157 | } 158 | } 159 | -------------------------------------------------------------------------------- /client/assets/cordova/config.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | eMeal 4 | eMeal - Demo Application 5 | 6 | Offering Solutions Software 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | -------------------------------------------------------------------------------- /client/assets/cordova/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "com.example.hello", 3 | "displayName": "HelloWorld", 4 | "version": "1.0.0", 5 | "description": "A sample Apache Cordova application that responds to the deviceready event.", 6 | "main": "index.js", 7 | "scripts": { 8 | "test": "echo \"Error: no test specified\" && exit 1" 9 | }, 10 | "keywords": [ 11 | "ecosystem:cordova" 12 | ], 13 | "author": "Apache Cordova Team", 14 | "license": "Apache-2.0", 15 | "dependencies": { 16 | "cordova-android": "^8.0.0", 17 | "cordova-plugin-camera": "^4.0.3", 18 | "cordova-plugin-crosswalk-webview": "^2.4.0", 19 | "cordova-plugin-device": "^2.0.2", 20 | "cordova-plugin-splashscreen": "^5.0.2", 21 | "cordova-plugin-statusbar": "^2.4.2", 22 | "cordova-plugin-whitelist": "^1.3.3", 23 | "cordova-plugin-x-toast": "^2.7.2", 24 | "cordova-windows": "^7.0.0" 25 | }, 26 | "cordova": { 27 | "plugins": { 28 | "cordova-plugin-whitelist": {}, 29 | "cordova-plugin-camera": {}, 30 | "cordova-plugin-statusbar": {}, 31 | "cordova-plugin-splashscreen": {}, 32 | "cordova-plugin-device": {}, 33 | "cordova-plugin-x-toast": {} 34 | }, 35 | "platforms": [ 36 | "android", 37 | "windows" 38 | ] 39 | } 40 | } -------------------------------------------------------------------------------- /client/assets/electron/cpuValues.js: -------------------------------------------------------------------------------- 1 | var os = require('os'); 2 | 3 | module.exports = {}; 4 | 5 | const getCPUUsage = (callback) => { 6 | 7 | var stats1 = getCpuValues(); 8 | var startIdle = stats1.idle; 9 | var startTotal = stats1.total; 10 | 11 | setTimeout(() => { 12 | var stats2 = getCpuValues(); 13 | var endIdle = stats2.idle; 14 | var endTotal = stats2.total; 15 | 16 | var idle = endIdle - startIdle; 17 | var total = endTotal - startTotal; 18 | var perc = idle / total; 19 | 20 | callback((1 - perc)); 21 | 22 | }, 500); 23 | } 24 | 25 | let getCpuValues = () => { 26 | var cpus = os.cpus(); 27 | 28 | var user = 0; 29 | var nice = 0; 30 | var sys = 0; 31 | var idle = 0; 32 | var irq = 0; 33 | var total = 0; 34 | 35 | for (var cpu in cpus) { 36 | if (!cpus.hasOwnProperty(cpu)) continue; 37 | user += cpus[cpu].times.user; 38 | nice += cpus[cpu].times.nice; 39 | sys += cpus[cpu].times.sys; 40 | irq += cpus[cpu].times.irq; 41 | idle += cpus[cpu].times.idle; 42 | } 43 | 44 | var total = user + nice + sys + idle + irq; 45 | 46 | return { 47 | 'idle': idle, 48 | 'total': total 49 | }; 50 | } 51 | 52 | module.exports.getCPUUsage = getCPUUsage; -------------------------------------------------------------------------------- /client/assets/electron/icon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FabianGosebrink/ASPNETCore-Angular-Ngrx/8c697557c83d8375a1ea06ab5fdfd19348e29204/client/assets/electron/icon.ico -------------------------------------------------------------------------------- /client/assets/electron/index.js: -------------------------------------------------------------------------------- 1 | const { app, BrowserWindow, globalShortcut } = require('electron'); 2 | 3 | const cpuValues = require('./cpuValues'); 4 | const trayIcon = require('./trayIcon'); 5 | 6 | let mainWindow = null; 7 | 8 | app.on('window-all-closed', () => { 9 | globalShortcut.unregisterAll(); 10 | if (process.platform !== 'darwin') { 11 | app.quit(); 12 | } 13 | }); 14 | 15 | let startSendCpuValues = () => { 16 | setInterval(() => { 17 | cpuValues.getCPUUsage(percentage => { 18 | console.log('sending to ipc channel: ' + percentage); 19 | if (mainWindow) { 20 | mainWindow.webContents.send( 21 | 'newCpuValue', 22 | (percentage * 100).toFixed(2) 23 | ); 24 | } 25 | }); 26 | }, 1000); 27 | }; 28 | 29 | const createWindow = () => { 30 | mainWindow = new BrowserWindow({ 31 | width: 1024, 32 | height: 768, 33 | webPreferences: { nodeIntegration: true } 34 | }); 35 | 36 | // mainWindow.loadURL('file://' + __dirname + '/index.html'); 37 | mainWindow.loadFile('index.html'); 38 | 39 | mainWindow.on('closed', function() { 40 | mainWindow = null; 41 | }); 42 | 43 | globalShortcut.register('CmdOrCtrl+Shift+i', () => { 44 | mainWindow.webContents.toggleDevTools(); 45 | }); 46 | 47 | trayIcon.buildTrayIcon(mainWindow); 48 | startSendCpuValues(); 49 | }; 50 | 51 | app.isReady() ? createWindow() : app.on('ready', createWindow); 52 | -------------------------------------------------------------------------------- /client/assets/electron/installerconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "icon": "assets/electron/icon.ico" 3 | } 4 | -------------------------------------------------------------------------------- /client/assets/electron/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "main": "index.js", 3 | "description": "An example app, built with Electron.", 4 | "version": "0.0.1", 5 | "license": "MIT", 6 | "name": "emeal", 7 | "author": { 8 | "name": "Fabian Gosebrink", 9 | "email": "fabian.gosebrink@offering.solutions", 10 | "url": "https://offering.solutions/" 11 | }, 12 | "private": true 13 | } 14 | -------------------------------------------------------------------------------- /client/assets/electron/trayIcon.js: -------------------------------------------------------------------------------- 1 | const { app, Menu, Tray } = require('electron'); 2 | const path = require('path'); 3 | 4 | module.exports = {}; 5 | 6 | let buildTrayIcon = mainWindow => { 7 | let trayIconPath = path.join(__dirname, 'icon.ico'); 8 | 9 | tray = new Tray(trayIconPath); 10 | tray.setToolTip('eMeal'); 11 | 12 | var contextMenu = Menu.buildFromTemplate([ 13 | { 14 | label: 'Open application', 15 | click: function() { 16 | mainWindow.show(); 17 | }, 18 | }, 19 | { 20 | label: 'Quit', 21 | click: function() { 22 | app.isQuiting = true; 23 | app.quit(); 24 | }, 25 | }, 26 | ]); 27 | 28 | tray.setContextMenu(contextMenu); 29 | }; 30 | 31 | module.exports.buildTrayIcon = buildTrayIcon; 32 | -------------------------------------------------------------------------------- /client/assets/img/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FabianGosebrink/ASPNETCore-Angular-Ngrx/8c697557c83d8375a1ea06ab5fdfd19348e29204/client/assets/img/icon.png -------------------------------------------------------------------------------- /client/assets/img/splash.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FabianGosebrink/ASPNETCore-Angular-Ngrx/8c697557c83d8375a1ea06ab5fdfd19348e29204/client/assets/img/splash.png -------------------------------------------------------------------------------- /client/assets/toggleHamburger.js: -------------------------------------------------------------------------------- 1 | // Make Hamburgermenu dissappear after clicking on it on mobile devices 2 | $(document).ready(function () { 3 | $(document).on('click', '.navbar-collapse.in', function (e) { 4 | if ($(e.target).is('a') && $(e.target).attr('class') != 'dropdown-toggle') { 5 | $(this).collapse('hide'); 6 | } 7 | }); 8 | }); -------------------------------------------------------------------------------- /client/browserslist: -------------------------------------------------------------------------------- 1 | # This file is used by the build system to adjust CSS and JS output to support the specified browsers below. 2 | # For additional information regarding the format and rule options, please see: 3 | # https://github.com/browserslist/browserslist#queries 4 | 5 | # You can see what browsers were selected by your queries by running: 6 | # npx browserslist 7 | 8 | > 0.5% 9 | last 2 versions 10 | Firefox ESR 11 | not dead 12 | not IE 9-11 # For IE 9-11 support, remove 'not'. -------------------------------------------------------------------------------- /client/e2e/protractor.conf.js: -------------------------------------------------------------------------------- 1 | // @ts-check 2 | // Protractor configuration file, see link for more information 3 | // https://github.com/angular/protractor/blob/master/lib/config.ts 4 | 5 | const { SpecReporter } = require('jasmine-spec-reporter'); 6 | 7 | /** 8 | * @type { import("protractor").Config } 9 | */ 10 | exports.config = { 11 | allScriptsTimeout: 11000, 12 | specs: [ 13 | './src/**/*.e2e-spec.ts' 14 | ], 15 | capabilities: { 16 | browserName: 'chrome' 17 | }, 18 | directConnect: true, 19 | baseUrl: 'http://localhost:4200/', 20 | framework: 'jasmine', 21 | jasmineNodeOpts: { 22 | showColors: true, 23 | defaultTimeoutInterval: 30000, 24 | print: function() {} 25 | }, 26 | onPrepare() { 27 | require('ts-node').register({ 28 | project: require('path').join(__dirname, './tsconfig.json') 29 | }); 30 | jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } })); 31 | } 32 | }; -------------------------------------------------------------------------------- /client/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('emeal app is running!'); 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 | -------------------------------------------------------------------------------- /client/e2e/src/app.po.ts: -------------------------------------------------------------------------------- 1 | import { browser, by, element } from 'protractor'; 2 | 3 | export class AppPage { 4 | navigateTo(): Promise { 5 | return browser.get(browser.baseUrl) as Promise; 6 | } 7 | 8 | getTitleText(): Promise { 9 | return element(by.css('app-root .content span')).getText() as Promise; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /client/e2e/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "../out-tsc/e2e", 5 | "module": "commonjs", 6 | "target": "es5", 7 | "types": [ 8 | "jasmine", 9 | "jasminewd2", 10 | "node" 11 | ] 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /client/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/emeal'), 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 | -------------------------------------------------------------------------------- /client/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "emeal", 3 | "version": "0.0.0", 4 | "description": "Cross Platform app with ngrx", 5 | "author": "Fabian Gosebrink", 6 | "scripts": { 7 | "ng": "ng", 8 | "start": "ng serve", 9 | "test": "ng test", 10 | "test-ci": "ng test --watch=false --browsers=ChromeHeadless", 11 | "lint": "./node_modules/.bin/tslint -c tslint.json -p tsconfig.json", 12 | "e2e": "ng e2e", 13 | "build": "ng build --prod --output-path=\".dist/web\"", 14 | "build-web": "npm run build", 15 | "build-and-pack-desktop": "npm run prepare-desktop && npm run pack-desktop && npm run build-desktop-installer", 16 | "build-desktop": "ng build --configuration=desktop --output-path=\".temp/electron\"", 17 | "prepare-desktop": "rimraf ./.temp/electron && rimraf .dist/desktop/ && npm run build-desktop && ncp assets/electron .temp/electron/", 18 | "pack-desktop": "electron-packager .temp/electron/ --electronVersion=4.0.4 --icon=\"assets/electron/icon\" --platform=win32,linux --out=./.dist/desktop/", 19 | "prepare-desktop-installer": "ncp ./package.json ./.dist/desktop/emeal-win32-x64/resources/app/package.json", 20 | "build-desktop-installer": "npm run prepare-desktop-installer && electron-installer-windows --src .dist/desktop/emeal-win32-x64/ --dest .dist/desktop/installer --config assets/electron/installerconfig.json", 21 | "build-mobile": "npm run mobile-prepare && npm run mobile-prepare-windows && npm run mobile-prepare-android && npm run mobile-generate-assets && npm run mobile-build && npm run copy-mobile-to-dist", 22 | "mobile-prepare": "rimraf .temp/mobile/ && ng build --configuration=mobile --output-path=\".temp/mobile/www\" && ncp assets/cordova .temp/mobile/ && rimraf .dist/mobile/", 23 | "mobile-prepare-android": "mkdirp .dist/mobile/android && cd .temp/mobile && cordova prepare android && cd ../..", 24 | "mobile-prepare-windows": "mkdirp .dist/mobile/windows && cd .temp/mobile && cordova prepare windows", 25 | "mobile-generate-assets": "ncp assets/img .temp/mobile/resources && cd .temp/mobile && cordova-res", 26 | "mobile-build": "cd .temp/mobile && cordova build && cd ../..", 27 | "copy-mobile-to-dist": "ncp .temp/mobile/platforms/android .dist/mobile/android && ncp .temp/mobile/platforms/windows .dist/mobile/windows && cd ../..", 28 | "build-all": "rimraf .dist && npm run build-web && npm run build-mobile && npm run build-and-pack-desktop", 29 | "bundle-report": "npm run build && webpack-bundle-analyzer .dist/web/stats.json", 30 | "cleanup": "rimraf .temp" 31 | }, 32 | "private": true, 33 | "dependencies": { 34 | "@angular/animations": "~9.0.0", 35 | "@angular/common": "~9.0.0", 36 | "@angular/compiler": "~9.0.0", 37 | "@angular/core": "~9.0.0", 38 | "@angular/forms": "~9.0.0", 39 | "@angular/platform-browser": "~9.0.0", 40 | "@angular/platform-browser-dynamic": "~9.0.0", 41 | "@angular/router": "~9.0.0", 42 | "rxjs": "~6.5.4", 43 | "tslib": "^1.10.0", 44 | "zone.js": "~0.10.2", 45 | "@aspnet/signalr": "^1.1.4", 46 | "@ngrx/effects": "8.6.0", 47 | "@ngrx/router-store": "8.6.0", 48 | "@ngrx/store": "8.6.0", 49 | "bootstrap": "^4.4.1", 50 | "cordova": "^9.0.0", 51 | "core-js": "^2.5.4", 52 | "electron": "8.0.0", 53 | "electron-installer-windows": "3.0.0", 54 | "font-awesome": "^4.7.0", 55 | "jquery": "^3.4.1", 56 | "ngx-electron": "2.2.0", 57 | "ngx-toastr": "^12.0.0", 58 | "rxjs-tslint": "^0.1.7" 59 | }, 60 | "devDependencies": { 61 | "@angular-devkit/build-angular": "~0.900.1", 62 | "@angular/cli": "~9.0.1", 63 | "@angular/compiler-cli": "~9.0.0", 64 | "@angular/language-service": "~9.0.0", 65 | "@types/node": "^12.11.1", 66 | "@types/jasmine": "~3.5.0", 67 | "@types/jasminewd2": "~2.0.3", 68 | "codelyzer": "^5.1.2", 69 | "jasmine-core": "~3.5.0", 70 | "jasmine-spec-reporter": "~4.2.1", 71 | "karma": "~4.3.0", 72 | "karma-chrome-launcher": "~3.1.0", 73 | "karma-coverage-istanbul-reporter": "~2.1.0", 74 | "karma-jasmine": "~2.0.1", 75 | "karma-jasmine-html-reporter": "^1.4.2", 76 | "protractor": "~5.4.3", 77 | "ts-node": "~8.3.0", 78 | "tslint": "~5.18.0", 79 | "typescript": "~3.7.5", 80 | "electron-packager": "14.2.1", 81 | "karma-mocha-reporter": "^2.2.5", 82 | "karma-phantomjs-launcher": "^1.0.4", 83 | "mkdirp": "^0.5.1", 84 | "ncp": "^2.0.0", 85 | "cordova-res": "^0.9.0" 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /client/src/app/app.component.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /client/src/app/app.component.ts: -------------------------------------------------------------------------------- 1 | import { Component } from '@angular/core'; 2 | import { Configuration } from './shared/configuration/app.configuration'; 3 | 4 | @Component({ 5 | selector: 'app-foodchooser', 6 | templateUrl: 'app.component.html' 7 | }) 8 | export class AppComponent { 9 | title: string; 10 | 11 | constructor(public configuration: Configuration) { 12 | this.title = configuration.title; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /client/src/app/app.module.ts: -------------------------------------------------------------------------------- 1 | import { NgModule } from '@angular/core'; 2 | import { BrowserModule } from '@angular/platform-browser'; 3 | import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; 4 | import { PreloadAllModules, RouterModule } from '@angular/router'; 5 | import { EffectsModule } from '@ngrx/effects'; 6 | import { 7 | RouterStateSerializer, 8 | StoreRouterConnectingModule 9 | } from '@ngrx/router-store'; 10 | import { StoreModule } from '@ngrx/store'; 11 | import { ToastrModule } from 'ngx-toastr'; 12 | import { NgxElectronModule } from 'ngx-electron'; 13 | import { AppComponent } from './app.component'; 14 | import { AppRoutes } from './app.routes'; 15 | import { CoreModule } from './core/core.module'; 16 | import { HomeModule } from './home/home.module'; 17 | import { SharedModule } from './shared/shared.module'; 18 | import { CustomSerializer, reducers } from './store'; 19 | 20 | @NgModule({ 21 | imports: [ 22 | BrowserAnimationsModule, 23 | BrowserModule, 24 | ToastrModule.forRoot(), 25 | RouterModule.forRoot(AppRoutes, { 26 | useHash: true, 27 | preloadingStrategy: PreloadAllModules 28 | }), 29 | SharedModule, 30 | NgxElectronModule, 31 | HomeModule, 32 | CoreModule.forRoot(), 33 | StoreModule.forRoot(reducers), 34 | EffectsModule.forRoot([]), 35 | StoreRouterConnectingModule.forRoot() 36 | ], 37 | providers: [{ provide: RouterStateSerializer, useClass: CustomSerializer }], 38 | declarations: [AppComponent], 39 | 40 | bootstrap: [AppComponent] 41 | }) 42 | export class AppModule {} 43 | -------------------------------------------------------------------------------- /client/src/app/app.routes.ts: -------------------------------------------------------------------------------- 1 | import { Routes } from '@angular/router'; 2 | 3 | export const AppRoutes: Routes = [ 4 | { path: '', redirectTo: 'home', pathMatch: 'full' }, 5 | { 6 | path: 'food', 7 | loadChildren: () => import('./food/food.module').then(m => m.FoodModule) 8 | }, 9 | { 10 | path: '**', 11 | redirectTo: 'home' 12 | } 13 | ]; 14 | -------------------------------------------------------------------------------- /client/src/app/core/core.module.ts: -------------------------------------------------------------------------------- 1 | import { CommonModule } from '@angular/common'; 2 | import { HTTP_INTERCEPTORS } from '@angular/common/http'; 3 | import { ModuleWithProviders, NgModule } from '@angular/core'; 4 | import { EffectsModule } from '@ngrx/effects'; 5 | import { StoreModule } from '@ngrx/store'; 6 | import { StandardHeaderInterceptor } from './interceptors'; 7 | import { CoreStoreFacade } from './store/core-store.facade'; 8 | import { effects } from './store/effects'; 9 | import { reducers } from './store/reducers'; 10 | 11 | @NgModule({ 12 | imports: [ 13 | CommonModule, 14 | StoreModule.forFeature('core', reducers), 15 | EffectsModule.forFeature(effects), 16 | ], 17 | }) 18 | export class CoreModule { 19 | static forRoot(): ModuleWithProviders { 20 | return { 21 | ngModule: CoreModule, 22 | providers: [ 23 | { 24 | provide: HTTP_INTERCEPTORS, 25 | useClass: StandardHeaderInterceptor, 26 | multi: true, 27 | }, 28 | ], 29 | }; 30 | } 31 | 32 | constructor(private facade: CoreStoreFacade) { 33 | this.facade.establishSignalRConnection(); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /client/src/app/core/data-services/food-data.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { HttpWrapperService } from './httpWrapper.service'; 3 | import { FoodItem } from '@app/shared/models/foodItem.model'; 4 | import { environment } from '@environments/environment'; 5 | import { ModelDescriptor } from '@app/shared/models/model.descriptor'; 6 | 7 | @Injectable({ providedIn: 'root' }) 8 | export class FoodDataService { 9 | private actionUrl: string; 10 | 11 | constructor(private http: HttpWrapperService) { 12 | this.actionUrl = environment.server + environment.apiUrl + 'foods/'; 13 | } 14 | 15 | getAllFood() { 16 | return this.http.get>(this.actionUrl); 17 | } 18 | 19 | getSingleFood(id: string) { 20 | return this.http.get(this.actionUrl + id); 21 | } 22 | 23 | addFood(foodItem: FoodItem) { 24 | foodItem.created = new Date(); 25 | 26 | return this.http.post(this.actionUrl, foodItem); 27 | } 28 | 29 | updateFood(id: string, foodToUpdate: FoodItem) { 30 | return this.http.put(this.actionUrl + id, foodToUpdate); 31 | } 32 | 33 | deleteFood(item: FoodItem) { 34 | return this.http.delete(this.actionUrl + item.id); 35 | } 36 | 37 | getRandomMeal() { 38 | return this.http.get>( 39 | this.actionUrl + 'getrandommeal/' 40 | ); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /client/src/app/core/data-services/httpWrapper.service.ts: -------------------------------------------------------------------------------- 1 | import { HttpClient } from '@angular/common/http'; 2 | import { Injectable } from '@angular/core'; 3 | import { Observable } from 'rxjs'; 4 | 5 | @Injectable({ providedIn: 'root' }) 6 | export class HttpWrapperService { 7 | constructor(private http: HttpClient) {} 8 | 9 | get(url: string): Observable { 10 | return this.http.get(url); 11 | } 12 | 13 | post(url: string, body: any): Observable { 14 | return this.http.post(url, body); 15 | } 16 | 17 | put(url: string, body: any): Observable { 18 | return this.http.put(url, body); 19 | } 20 | 21 | delete(url: string): Observable { 22 | return this.http.delete(url); 23 | } 24 | 25 | patch(url: string, body: string): Observable { 26 | return this.http.patch(url, body); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /client/src/app/core/data-services/ingredient-data.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { Observable } from 'rxjs'; 3 | import { HttpWrapperService } from './httpWrapper.service'; 4 | import { environment } from '@environments/environment'; 5 | import { Ingredient } from '@app/shared/models/ingredient.model'; 6 | 7 | @Injectable({ providedIn: 'root' }) 8 | export class IngredientsDataService { 9 | private actionUrl: string; 10 | private endpoint = 'ingredients'; 11 | 12 | constructor(private http: HttpWrapperService) { 13 | this.actionUrl = environment.server + environment.apiUrl + 'foods/'; 14 | } 15 | 16 | getIngredientsForFood(foodId: string): Observable { 17 | return this.http.get( 18 | `${this.actionUrl}${foodId}/${this.endpoint}` 19 | ); 20 | } 21 | 22 | add(ingredient: Ingredient, foodId: string): Observable { 23 | return this.http.post( 24 | `${this.actionUrl}${foodId}/${this.endpoint}`, 25 | ingredient 26 | ); 27 | } 28 | 29 | delete(ingredient: Ingredient, foodId: string) { 30 | return this.http.delete( 31 | `${this.actionUrl}${foodId}/${this.endpoint}/${ingredient.id}` 32 | ); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /client/src/app/core/interceptors/index.ts: -------------------------------------------------------------------------------- 1 | export * from './standard-header.interceptor'; 2 | -------------------------------------------------------------------------------- /client/src/app/core/interceptors/standard-header.interceptor.ts: -------------------------------------------------------------------------------- 1 | import { 2 | HttpEvent, 3 | HttpHandler, 4 | HttpInterceptor, 5 | HttpRequest 6 | } from '@angular/common/http'; 7 | import { Injectable } from '@angular/core'; 8 | import { Observable } from 'rxjs'; 9 | 10 | @Injectable() 11 | export class StandardHeaderInterceptor implements HttpInterceptor { 12 | intercept( 13 | req: HttpRequest, 14 | next: HttpHandler 15 | ): Observable> { 16 | if (!req.headers.has('Content-Type')) { 17 | req = req.clone({ 18 | headers: req.headers.set('Content-Type', 'application/json') 19 | }); 20 | } 21 | 22 | req = req.clone({ headers: req.headers.set('Accept', 'application/json') }); 23 | return next.handle(req); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /client/src/app/core/services/abstract-camera.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { Observable } from 'rxjs'; 3 | import { environment } from '../../../environments/environment'; 4 | import { DesktopCameraService } from './desktop-camera.service'; 5 | import { MobileCameraService } from './mobile-camera.service'; 6 | 7 | export function cameraFactory(): AbstractCameraService { 8 | return environment.mobile 9 | ? new MobileCameraService() 10 | : new DesktopCameraService(); 11 | } 12 | 13 | interface ICameraService { 14 | getPhoto(): Observable; 15 | } 16 | 17 | @Injectable({ 18 | providedIn: 'root', 19 | useFactory: cameraFactory, 20 | }) 21 | export abstract class AbstractCameraService implements ICameraService { 22 | abstract getPhoto(): Observable; 23 | } 24 | -------------------------------------------------------------------------------- /client/src/app/core/services/abstract-notification.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { environment } from '@environments/environment'; 3 | import { ToastrService } from 'ngx-toastr'; 4 | import { DesktopNotificationService } from './desktop-notification.service'; 5 | import { MobileNotificationService } from './mobile-notification.service'; 6 | import { WebNotificationService } from './web-notification.service'; 7 | 8 | export function notificationFactory( 9 | toastrService: ToastrService 10 | ): AbstractNotificationService { 11 | if (environment.desktop) { 12 | return new DesktopNotificationService(); 13 | //return new WebNotificationService(toastrService); 14 | } 15 | 16 | if (environment.mobile) { 17 | return new MobileNotificationService(); 18 | } 19 | 20 | return new WebNotificationService(toastrService); 21 | } 22 | 23 | export interface INotificationService { 24 | showError(title: string, message: string, icon?: string); 25 | 26 | showInfo(title: string, message: string, icon?: string); 27 | 28 | showSuccess(title: string, message: string, icon?: string); 29 | 30 | showWarning(title: string, message: string, icon?: string); 31 | } 32 | 33 | @Injectable({ 34 | providedIn: 'root', 35 | useFactory: notificationFactory, 36 | deps: [ToastrService] 37 | }) 38 | export abstract class AbstractNotificationService 39 | implements INotificationService { 40 | abstract showError(title: string, message: string, icon?: string); 41 | 42 | abstract showInfo(title: string, message: string, icon?: string); 43 | 44 | abstract showSuccess(title: string, message: string, icon?: string); 45 | 46 | abstract showWarning(title: string, message: string, icon?: string); 47 | } 48 | -------------------------------------------------------------------------------- /client/src/app/core/services/currentUser.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { StorageService } from './storage.service'; 3 | 4 | @Injectable({ providedIn: 'root' }) 5 | export class CurrentUserService { 6 | constructor(private storageService: StorageService) {} 7 | 8 | get token(): string { 9 | const token = this.storageService.getItem('auth'); 10 | return token; 11 | } 12 | 13 | set token(token: string) { 14 | if (!token) { 15 | this.storageService.removeItem('auth'); 16 | } else { 17 | this.storageService.setItem('auth', token); 18 | } 19 | } 20 | 21 | get username() { 22 | const username = this.storageService.getItem('username'); 23 | return username; 24 | } 25 | 26 | set username(username: string) { 27 | if (!username) { 28 | this.storageService.removeItem('username'); 29 | } else { 30 | this.storageService.setItem('username', username); 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /client/src/app/core/services/desktop-camera.service.ts: -------------------------------------------------------------------------------- 1 | import { Observable } from 'rxjs'; 2 | import { AbstractCameraService } from './abstract-camera.service'; 3 | 4 | declare const window: any; 5 | 6 | export class DesktopCameraService implements AbstractCameraService { 7 | private getMediaDevices(): any { 8 | const mediaDevices = 9 | (window.navigator.mozGetUserMedia || window.navigator.webkitGetUserMedia 10 | ? { 11 | getUserMedia: function(options: any) { 12 | return new Promise((resolve, reject) => { 13 | ( 14 | window.navigator.mozGetUserMedia || 15 | window.navigator.webkitGetUserMedia 16 | ).call(window.navigator, options, resolve, reject); 17 | }); 18 | }, 19 | } 20 | : null) || window.navigator.mediaDevices; 21 | 22 | return mediaDevices; 23 | } 24 | 25 | getPhoto(): Observable { 26 | return Observable.create((observer: any) => { 27 | this.getMediaDevices() 28 | .getUserMedia({ video: true, audio: false }) 29 | .then( 30 | (stream: any) => { 31 | const doc = document; 32 | const videoElement = doc.createElement('video'); 33 | videoElement.srcObject = stream; 34 | videoElement.play(); 35 | 36 | const takePhotoInternal = () => { 37 | const canvasElement = doc.createElement('canvas'); 38 | canvasElement.setAttribute( 39 | 'width', 40 | videoElement.videoWidth.toString() 41 | ); 42 | canvasElement.setAttribute( 43 | 'height', 44 | videoElement.videoHeight.toString() 45 | ); 46 | 47 | setTimeout(() => { 48 | const context = canvasElement.getContext('2d'); 49 | context.drawImage( 50 | videoElement, 51 | 0, 52 | 0, 53 | videoElement.videoWidth, 54 | videoElement.videoHeight 55 | ); 56 | 57 | const url = canvasElement.toDataURL('image/png'); 58 | 59 | videoElement.pause(); 60 | 61 | if (stream.stop) { 62 | stream.stop(); 63 | } 64 | 65 | if (stream.getAudioTracks) { 66 | stream.getAudioTracks().forEach((track: any) => { 67 | track.stop(); 68 | }); 69 | } 70 | 71 | if (stream.getVideoTracks) { 72 | stream.getVideoTracks().forEach((track: any) => { 73 | track.stop(); 74 | }); 75 | } 76 | 77 | observer.next(url); 78 | observer.complete(); 79 | }, 500); 80 | }; 81 | 82 | if (videoElement.readyState >= videoElement.HAVE_FUTURE_DATA) { 83 | takePhotoInternal(); 84 | } else { 85 | videoElement.addEventListener( 86 | 'canplay', 87 | function() { 88 | takePhotoInternal(); 89 | }, 90 | false 91 | ); 92 | } 93 | }, 94 | (error: any) => { 95 | console.log(error); 96 | } 97 | ); 98 | }); 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /client/src/app/core/services/desktop-cpuValue.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { ElectronService } from 'ngx-electron'; 3 | import { Subject } from 'rxjs'; 4 | import { environment } from '../../../environments/environment'; 5 | 6 | @Injectable({ 7 | providedIn: 'root', 8 | }) 9 | export class CpuValueService { 10 | onNewCpuValue = new Subject(); 11 | 12 | constructor(private electronService: ElectronService) { 13 | if (environment.desktop) { 14 | this.registerCpuEvent(); 15 | } 16 | } 17 | 18 | private registerCpuEvent() { 19 | if (this.electronService.ipcRenderer) { 20 | this.electronService.ipcRenderer.on( 21 | 'newCpuValue', 22 | (event: any, data: any) => { 23 | this.onNewCpuValue.next(data); 24 | } 25 | ); 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /client/src/app/core/services/desktop-notification.service.ts: -------------------------------------------------------------------------------- 1 | import { AbstractNotificationService } from './abstract-notification.service'; 2 | 3 | export class DesktopNotificationService implements AbstractNotificationService { 4 | showError(title: string, message: string, icon?: string) { 5 | this.showNotification('Error', title, message, icon); 6 | } 7 | 8 | showInfo(title: string, message: string, icon?: string) { 9 | this.showNotification('Info', title, message, icon); 10 | } 11 | 12 | showWait(title: string, message: string, icon?: string) { 13 | this.showNotification('Wait', title, message, icon); 14 | } 15 | 16 | showSuccess(title: string, message: string, icon?: string) { 17 | this.showNotification('Success', title, message, icon); 18 | } 19 | 20 | showWarning(title: string, message: string, icon?: string) { 21 | this.showNotification('Warning', title, message, icon); 22 | } 23 | 24 | private showNotification( 25 | type: string, 26 | title: string, 27 | message: string, 28 | icon?: string 29 | ): void { 30 | if (!Notification) { 31 | alert( 32 | 'Desktop notifications not available in your browser. Try Chromium.' 33 | ); 34 | return; 35 | } 36 | 37 | const messageBody: NotificationOptions = {}; 38 | 39 | messageBody.body = message; 40 | 41 | if (icon) { 42 | messageBody.icon = icon; 43 | } 44 | 45 | const titleToShow = `${type} : ${title}`; 46 | 47 | Notification.requestPermission().then(() => { 48 | const myNotification = new Notification(titleToShow, messageBody); 49 | }); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /client/src/app/core/services/mobile-camera.service.ts: -------------------------------------------------------------------------------- 1 | import { Observable, Observer } from 'rxjs'; 2 | import { AbstractCameraService } from './abstract-camera.service'; 3 | 4 | declare let window: any; 5 | 6 | export class MobileCameraService implements AbstractCameraService { 7 | getPhoto(): Observable { 8 | return Observable.create((observer: Observer) => { 9 | const camera = window.navigator.camera; 10 | const options = { 11 | quality: 100, 12 | destinationType: camera.DestinationType.DATA_URL, 13 | sourceType: camera.PictureSourceType.CAMERA, 14 | encodingType: camera.EncodingType.PNG, 15 | pictureSourceType: camera.PictureSourceType.CAMERA, 16 | saveToPhotoAlbum: false, 17 | targetWidth: 640, 18 | targetHeight: 640, 19 | correctOrientation: true, 20 | }; 21 | 22 | camera.getPicture( 23 | (imageData: any) => { 24 | observer.next('data:image/png;base64,' + imageData); 25 | observer.complete(); 26 | }, 27 | (error: any) => { 28 | observer.error(error); 29 | observer.complete(); 30 | }, 31 | options 32 | ); 33 | }); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /client/src/app/core/services/mobile-notification.service.ts: -------------------------------------------------------------------------------- 1 | import { AbstractNotificationService } from './abstract-notification.service'; 2 | 3 | declare let window: any; 4 | export class MobileNotificationService implements AbstractNotificationService { 5 | private RGB_COLOR_ERROR = '#FF0000'; 6 | private RGB_COLOR_SUCCESS = '#32CD32'; 7 | private RGB_COLOR_NEUTRAL = '#333333'; 8 | private RGB_COLOR_WARNING = '#FFA500'; 9 | 10 | showError(title: string, message: string, icon?: string) { 11 | this.showNotification(this.RGB_COLOR_ERROR, message); 12 | } 13 | 14 | showInfo(title: string, message: string, icon?: string) { 15 | this.showNotification(this.RGB_COLOR_NEUTRAL, message); 16 | } 17 | 18 | showWait(title: string, message: string, icon?: string) { 19 | this.showNotification(this.RGB_COLOR_NEUTRAL, message); 20 | } 21 | 22 | showSuccess(title: string, message: string, icon?: string) { 23 | this.showNotification(this.RGB_COLOR_SUCCESS, message); 24 | } 25 | 26 | showWarning(title: string, message: string, icon?: string) { 27 | this.showNotification(this.RGB_COLOR_WARNING, message); 28 | } 29 | 30 | private showNotification(backgroundColor: string, message: string): void { 31 | window.plugins.toast.showWithOptions({ 32 | message: message, 33 | duration: 'long', // which is 2000 ms. "long" is 4000. Or specify the nr of ms yourself. 34 | position: 'bottom', 35 | addPixelsY: -40, // added a negative value to move it up a bit (default 0), 36 | styling: { 37 | backgroundColor: backgroundColor, // '#FF0000' make sure you use #RRGGBB. Default #333333 38 | }, 39 | }); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /client/src/app/core/services/platform-information.provider.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | 3 | declare let window: any; 4 | 5 | @Injectable({ 6 | providedIn: 'root', 7 | }) 8 | export class PlatformInformationProvider { 9 | private _iOS: boolean; 10 | private _isAndroid: boolean; 11 | 12 | get isMobileWeb(): boolean { 13 | return window.innerWidth <= 768; 14 | } 15 | 16 | get isIOS(): boolean { 17 | return this._iOS; 18 | } 19 | 20 | get isAndroid(): boolean { 21 | return this._isAndroid; 22 | } 23 | 24 | get userAgent(): boolean { 25 | return window.navigator.userAgent; 26 | } 27 | 28 | get platformName(): any { 29 | if (!window.device) { 30 | return 'No window.device'; 31 | } 32 | return `${window.device.platform} ${window.device.model}`; 33 | } 34 | 35 | constructor() { 36 | this.guessPlatform(); 37 | } 38 | 39 | private guessPlatform(): void { 40 | this._iOS = window.cordova && window.cordova.platformId === 'ios'; 41 | this._isAndroid = window.cordova && window.cordova.platformId === 'android'; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /client/src/app/core/services/signalR.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { HubConnection, HubConnectionBuilder, LogLevel } from '@aspnet/signalr'; 3 | import { Observable, Observer } from 'rxjs'; 4 | import { environment } from '../../../environments/environment'; 5 | import { FoodStoreFacade } from '../../food/store/food-store.facade'; 6 | import { Ingredient } from '../../shared/models/ingredient.model'; 7 | 8 | @Injectable({ 9 | providedIn: 'root', 10 | }) 11 | export class SignalRService { 12 | private foodHubConnection: HubConnection; 13 | 14 | constructor(private facade: FoodStoreFacade) {} 15 | 16 | initializeConnection(): Observable { 17 | this.foodHubConnection = new HubConnectionBuilder() 18 | .withUrl(environment.server + 'foodhub') 19 | .configureLogging(LogLevel.Information) 20 | .build(); 21 | 22 | this.registerOnServerEvents(); 23 | 24 | return Observable.create((observer: Observer) => { 25 | this.foodHubConnection 26 | .start() 27 | .then(() => { 28 | console.log('Hub connection started'); 29 | observer.next(true); 30 | observer.complete(); 31 | }) 32 | .catch(err => { 33 | console.log('Error while establishing connection', err); 34 | observer.error(err); 35 | }); 36 | }); 37 | } 38 | 39 | private registerOnServerEvents(): void { 40 | this.foodHubConnection.on('food-added', (data: any) => { 41 | this.facade.receivedFoodData(data); 42 | }); 43 | 44 | this.foodHubConnection.on('food-deleted', (data: any) => { 45 | this.facade.receivedFoodDeleted(data); 46 | }); 47 | 48 | this.foodHubConnection.on('food-updated', (data: any) => { 49 | this.facade.receivedFoodUpdated(data); 50 | }); 51 | 52 | this.foodHubConnection.on( 53 | 'ingredient-added', 54 | (foodId: string, ingredient: Ingredient) => { 55 | this.facade.receivedIngredientAdded(ingredient); 56 | } 57 | ); 58 | 59 | this.foodHubConnection.on( 60 | 'ingredient-deleted', 61 | (foodId: string, ingredientId: string) => { 62 | this.facade.receivedIngredientDeleted(ingredientId); 63 | } 64 | ); 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /client/src/app/core/services/sort.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | 3 | @Injectable({ 4 | providedIn: 'root', 5 | }) 6 | export class Sorter { 7 | private direction: number; 8 | private key: string; 9 | 10 | constructor() { 11 | this.direction = -1; 12 | } 13 | 14 | sort(key: string, data: any[]) { 15 | if (this.key === key) { 16 | this.direction = this.direction * -1; 17 | } else { 18 | this.direction = 1; 19 | } 20 | 21 | this.key = key; 22 | 23 | data.sort((a: any, b: any) => { 24 | if (a[key] === b[key]) { 25 | return 0; 26 | } else if (a[key] > b[key]) { 27 | return 1 * this.direction; 28 | } else { 29 | return -1 * this.direction; 30 | } 31 | }); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /client/src/app/core/services/storage.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | 3 | const APP_PREFIX = 'OS-'; 4 | 5 | @Injectable({ 6 | providedIn: 'root', 7 | }) 8 | export class StorageService { 9 | private _storage: Storage; 10 | 11 | static loadInitialState() { 12 | const isAuthenticated = localStorage.getItem(`${APP_PREFIX}auth`); 13 | 14 | return { 15 | isAuthenticated: !!isAuthenticated, 16 | pending: false, 17 | signalRConnectionEstablished: false, 18 | }; 19 | } 20 | 21 | constructor() { 22 | this._storage = localStorage; 23 | } 24 | 25 | setItem(key: string, value: any): void { 26 | this._storage.setItem(`${APP_PREFIX}${key}`, JSON.stringify(value)); 27 | } 28 | 29 | removeItem(key: string): void { 30 | this._storage.removeItem(`${APP_PREFIX}${key}`); 31 | } 32 | 33 | getItem(key: string): any { 34 | return JSON.parse(localStorage.getItem(`${APP_PREFIX}${key}`)); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /client/src/app/core/services/web-notification.service.ts: -------------------------------------------------------------------------------- 1 | import { ToastrService } from 'ngx-toastr'; 2 | import { AbstractNotificationService } from './abstract-notification.service'; 3 | 4 | export class WebNotificationService implements AbstractNotificationService { 5 | constructor(private toastr: ToastrService) {} 6 | 7 | showError(title: string, message: string, icon?: string) { 8 | this.toastr.error(message, title); 9 | } 10 | 11 | showInfo(title: string, message: string, icon?: string) { 12 | this.toastr.info(message, title); 13 | } 14 | 15 | showSuccess(title: string, message: string, icon?: string) { 16 | this.toastr.success(message, title); 17 | } 18 | 19 | showWarning(title: string, message: string, icon?: string) { 20 | this.toastr.warning(message, title); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /client/src/app/core/store/actions/core.actions.ts: -------------------------------------------------------------------------------- 1 | import { Action } from '@ngrx/store'; 2 | 3 | export const SIGNALR_ESTABLISH_CONNECTION = 4 | '[Core] SIGNALR_ESTABLISH_CONNECTION'; 5 | export const SIGNALR_ESTABLISHED = '[Core] SIGNALR_ESTABLISHED'; 6 | export const SIGNALR_FAILED = '[Core] SIGNALR_FAILED'; 7 | 8 | export class SignalREstablishConnectionAction implements Action { 9 | readonly type = SIGNALR_ESTABLISH_CONNECTION; 10 | constructor() {} 11 | } 12 | 13 | export class SignalREstablishedAction implements Action { 14 | readonly type = SIGNALR_ESTABLISHED; 15 | constructor() {} 16 | } 17 | 18 | export class SignalRFailedAction implements Action { 19 | readonly type = SIGNALR_FAILED; 20 | constructor(public errorMessage: any) {} 21 | } 22 | 23 | export type CoreActions = SignalREstablishedAction | SignalRFailedAction; 24 | -------------------------------------------------------------------------------- /client/src/app/core/store/actions/index.ts: -------------------------------------------------------------------------------- 1 | export * from './core.actions'; 2 | -------------------------------------------------------------------------------- /client/src/app/core/store/core-store.facade.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { select, Store } from '@ngrx/store'; 3 | import * as fromActions from './actions'; 4 | import * as fromReducers from './reducers'; 5 | import * as fromSelectors from './selectors'; 6 | 7 | @Injectable({ providedIn: 'root' }) 8 | export class CoreStoreFacade { 9 | loginPending$ = this.store.pipe(select(fromSelectors.getPending)); 10 | 11 | constructor(private store: Store) {} 12 | 13 | establishSignalRConnection() { 14 | this.store.dispatch(new fromActions.SignalREstablishConnectionAction()); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /client/src/app/core/store/effects/core.effects.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { Router } from '@angular/router'; 3 | import { Actions, Effect, ofType } from '@ngrx/effects'; 4 | import { of } from 'rxjs'; 5 | import { catchError, map, switchMap, tap } from 'rxjs/operators'; 6 | import { AbstractNotificationService } from '../../services/abstract-notification.service'; 7 | import { SignalRService } from '../../services/signalR.service'; 8 | import * as CoreActions from '../actions/core.actions'; 9 | 10 | @Injectable() 11 | export class CoreEffects { 12 | @Effect() 13 | establishSignalRConnection$ = this.actions$.pipe( 14 | ofType(CoreActions.SIGNALR_ESTABLISH_CONNECTION), 15 | switchMap((action: CoreActions.SignalREstablishConnectionAction) => { 16 | return this.signalRService.initializeConnection().pipe( 17 | tap(() => 18 | this.notificationService.showInfo('SignalR', 'Connection established') 19 | ), 20 | map(() => new CoreActions.SignalREstablishedAction()), 21 | catchError((error: any) => { 22 | this.notificationService.showError('SignalR', error); 23 | return of(new CoreActions.SignalRFailedAction(error)); 24 | }) 25 | ); 26 | }) 27 | ); 28 | 29 | constructor( 30 | private notificationService: AbstractNotificationService, 31 | private signalRService: SignalRService, 32 | private actions$: Actions, 33 | private router: Router 34 | ) {} 35 | } 36 | -------------------------------------------------------------------------------- /client/src/app/core/store/effects/index.ts: -------------------------------------------------------------------------------- 1 | import { CoreEffects } from './core.effects'; 2 | 3 | export const effects: any[] = [CoreEffects]; 4 | 5 | export * from './core.effects'; 6 | -------------------------------------------------------------------------------- /client/src/app/core/store/reducers/core.reducer.ts: -------------------------------------------------------------------------------- 1 | import { StorageService } from '../../services/storage.service'; 2 | import * as fromCore from '../actions/core.actions'; 3 | 4 | export interface CoreState { 5 | signalRConnectionEstablished: boolean; 6 | pending: boolean; 7 | } 8 | 9 | export const initialState: CoreState = StorageService.loadInitialState(); 10 | 11 | export function coreReducer( 12 | state = initialState, 13 | action: fromCore.CoreActions 14 | ): CoreState { 15 | switch (action.type) { 16 | case fromCore.SIGNALR_ESTABLISHED: { 17 | return { ...state, signalRConnectionEstablished: true }; 18 | } 19 | 20 | case fromCore.SIGNALR_FAILED: { 21 | return { ...state, signalRConnectionEstablished: false }; 22 | } 23 | 24 | default: { 25 | return state; 26 | } 27 | } 28 | } 29 | 30 | export const getPending = (state: CoreState) => state.pending; 31 | -------------------------------------------------------------------------------- /client/src/app/core/store/reducers/index.ts: -------------------------------------------------------------------------------- 1 | import * as fromCore from './core.reducer'; 2 | import { ActionReducerMap, createFeatureSelector } from '@ngrx/store'; 3 | 4 | export interface CoreState { 5 | core: fromCore.CoreState; 6 | } 7 | 8 | export const reducers: ActionReducerMap = { 9 | core: fromCore.coreReducer 10 | }; 11 | 12 | export const getCoreState = createFeatureSelector('core'); 13 | -------------------------------------------------------------------------------- /client/src/app/core/store/selectors/core.selectors.ts: -------------------------------------------------------------------------------- 1 | import { createSelector } from '@ngrx/store'; 2 | import * as fromFeature from '../reducers'; 3 | import * as fromCore from '../reducers/core.reducer'; 4 | 5 | export const getCompleteCoreState = createSelector( 6 | fromFeature.getCoreState, 7 | (state: fromFeature.CoreState) => state.core 8 | ); 9 | 10 | export const getPending = createSelector( 11 | getCompleteCoreState, 12 | fromCore.getPending 13 | ); 14 | -------------------------------------------------------------------------------- /client/src/app/core/store/selectors/index.ts: -------------------------------------------------------------------------------- 1 | export * from './core.selectors'; 2 | -------------------------------------------------------------------------------- /client/src/app/food/container/food-details/food-details.component.html: -------------------------------------------------------------------------------- 1 | 2 |
3 |
4 |
5 | back 6 |
7 | 8 |
9 |
10 |
11 | 12 |
13 | 20 |
21 |
22 | 23 |
24 | 27 |
28 | 35 |
36 |
37 | 38 |
39 | 42 |
43 | 50 |
51 |
52 |
53 |
54 | 55 |
56 |
57 |
58 |
59 | -------------------------------------------------------------------------------- /client/src/app/food/container/food-details/food-details.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { Observable } from 'rxjs'; 3 | import { FoodItem } from '../../../shared/models/foodItem.model'; 4 | import { FoodStoreFacade } from '../../store/food-store.facade'; 5 | 6 | @Component({ 7 | selector: 'app-food-details', 8 | templateUrl: './food-details.component.html', 9 | }) 10 | export class FoodDetailsComponent implements OnInit { 11 | selectedItem$: Observable; 12 | 13 | constructor(private facade: FoodStoreFacade) {} 14 | 15 | ngOnInit() { 16 | this.selectedItem$ = this.facade.selectedFood$; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /client/src/app/food/container/index.ts: -------------------------------------------------------------------------------- 1 | import { FoodDetailsComponent } from './food-details/food-details.component'; 2 | import { IngredientsComponent } from './ingredients/ingredients.component'; 3 | import { MainFoodComponent } from './main-food/main-food.component'; 4 | 5 | export const allContainerComponents: any[] = [ 6 | MainFoodComponent, 7 | FoodDetailsComponent, 8 | IngredientsComponent, 9 | ]; 10 | 11 | export * from './food-details/food-details.component'; 12 | export * from './ingredients/ingredients.component'; 13 | export * from './main-food/main-food.component'; 14 | -------------------------------------------------------------------------------- /client/src/app/food/container/ingredients/ingredients.component.css: -------------------------------------------------------------------------------- 1 | li { 2 | list-style: none; 3 | } 4 | -------------------------------------------------------------------------------- /client/src/app/food/container/ingredients/ingredients.component.html: -------------------------------------------------------------------------------- 1 |

Ingredients

2 |
7 | 13 |
14 |
15 | 16 | 20 | -------------------------------------------------------------------------------- /client/src/app/food/container/ingredients/ingredients.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { async, ComponentFixture, TestBed } from '@angular/core/testing'; 2 | import { ReactiveFormsModule } from '@angular/forms'; 3 | import { RouterTestingModule } from '@angular/router/testing'; 4 | import { combineReducers, StoreModule } from '@ngrx/store'; 5 | import * as fromReducers from '../../../store/reducers'; 6 | import { IngredientListComponent } from '../../presentational/ingredient-list/ingredient-list.component'; 7 | import * as fromFeatureReducers from '../../store/reducers'; 8 | import { IngredientsComponent } from './ingredients.component'; 9 | 10 | describe('IngredientsComponent', () => { 11 | let component: IngredientsComponent; 12 | let fixture: ComponentFixture; 13 | 14 | beforeEach(async(() => { 15 | TestBed.configureTestingModule({ 16 | imports: [ 17 | RouterTestingModule, 18 | ReactiveFormsModule, 19 | StoreModule.forRoot({ 20 | ...fromReducers.reducers, 21 | food: combineReducers(fromFeatureReducers.reducers), 22 | }), 23 | ], 24 | declarations: [IngredientsComponent, IngredientListComponent], 25 | }).compileComponents(); 26 | })); 27 | 28 | beforeEach(() => { 29 | fixture = TestBed.createComponent(IngredientsComponent); 30 | component = fixture.componentInstance; 31 | fixture.detectChanges(); 32 | }); 33 | 34 | it('should create', () => { 35 | expect(component).toBeTruthy(); 36 | }); 37 | }); 38 | -------------------------------------------------------------------------------- /client/src/app/food/container/ingredients/ingredients.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { FormControl, FormGroup, Validators } from '@angular/forms'; 3 | import { ActivatedRoute } from '@angular/router'; 4 | import { Observable } from 'rxjs'; 5 | import { map } from 'rxjs/operators'; 6 | import { Ingredient } from '../../../shared/models/ingredient.model'; 7 | import { FoodStoreFacade } from '../../store/food-store.facade'; 8 | 9 | @Component({ 10 | selector: 'app-ingredients', 11 | templateUrl: './ingredients.component.html', 12 | styleUrls: ['./ingredients.component.css'], 13 | }) 14 | export class IngredientsComponent implements OnInit { 15 | ingredients$: Observable; 16 | form: FormGroup; 17 | 18 | constructor(private facade: FoodStoreFacade, private route: ActivatedRoute) {} 19 | 20 | ngOnInit() { 21 | this.form = new FormGroup({ 22 | description: new FormControl('', Validators.required), 23 | }); 24 | 25 | this.ingredients$ = this.facade.ingredients$; 26 | 27 | this.route.params.pipe(map(p => p.foodId)).subscribe((foodId: string) => { 28 | this.facade.loadAllIngredients(foodId); 29 | }); 30 | } 31 | 32 | addIngredient() { 33 | if (!this.form.valid) { 34 | return; 35 | } 36 | 37 | const foodId = this.route.snapshot.params['foodId']; 38 | 39 | this.facade.addIngredient(this.form.value, foodId); 40 | 41 | this.form.reset(); 42 | } 43 | 44 | delete(ingredient: Ingredient) { 45 | const foodId = this.route.snapshot.params['foodId']; 46 | this.facade.deleteIngredient(ingredient, foodId); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /client/src/app/food/container/main-food/main-food.component.html: -------------------------------------------------------------------------------- 1 |
2 | 7 |
8 | 13 |
14 | 15 | -------------------------------------------------------------------------------- /client/src/app/food/container/main-food/main-food.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { Observable } from 'rxjs'; 3 | import { FoodItem } from '../../../shared/models/foodItem.model'; 4 | import { FoodStoreFacade } from '../../store/food-store.facade'; 5 | 6 | @Component({ 7 | selector: 'app-main-food-component', 8 | templateUrl: './main-food.component.html' 9 | }) 10 | export class MainFoodComponent implements OnInit { 11 | foods$: Observable; 12 | selectedItem: FoodItem; 13 | 14 | constructor(private facade: FoodStoreFacade) {} 15 | 16 | ngOnInit() { 17 | this.foods$ = this.facade.allFoods$; 18 | this.facade.loadAllFoods(); 19 | } 20 | 21 | setCurrentlySelectedFood(foodItem: FoodItem) { 22 | this.selectedItem = foodItem; 23 | } 24 | 25 | addFood(foodItem: FoodItem) { 26 | this.facade.addFood(foodItem); 27 | this.selectedItem = null; 28 | } 29 | 30 | updateFood(foodItem: FoodItem) { 31 | this.facade.updateFood(foodItem); 32 | this.selectedItem = null; 33 | } 34 | 35 | deleteFood(foodItem: FoodItem) { 36 | this.facade.deleteFood(foodItem); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /client/src/app/food/food.module.ts: -------------------------------------------------------------------------------- 1 | import { CommonModule } from '@angular/common'; 2 | import { NgModule } from '@angular/core'; 3 | import { FormsModule, ReactiveFormsModule } from '@angular/forms'; 4 | import { RouterModule } from '@angular/router'; 5 | import { EffectsModule } from '@ngrx/effects'; 6 | import { StoreModule } from '@ngrx/store'; 7 | import { SharedModule } from '../shared/shared.module'; 8 | import { allContainerComponents } from './container'; 9 | import { FoodRoutes } from './food.routes'; 10 | import { FilterPipe } from './pipes/filter.pipe'; 11 | import { allPresComponents } from './presentational'; 12 | import { effects } from './store/effects'; 13 | import { reducers } from './store/reducers'; 14 | import { IsInRangeValidator } from './validators/isInRange.validator'; 15 | import { IsNumberValidator } from './validators/isNumber.validator'; 16 | 17 | @NgModule({ 18 | imports: [ 19 | CommonModule, 20 | FormsModule, 21 | SharedModule, 22 | RouterModule.forChild(FoodRoutes), 23 | StoreModule.forFeature('food', reducers), 24 | EffectsModule.forFeature(effects), 25 | ReactiveFormsModule, 26 | ], 27 | 28 | declarations: [ 29 | ...allContainerComponents, 30 | ...allPresComponents, 31 | 32 | IsInRangeValidator, 33 | IsNumberValidator, 34 | FilterPipe, 35 | ], 36 | 37 | exports: [], 38 | }) 39 | export class FoodModule {} 40 | -------------------------------------------------------------------------------- /client/src/app/food/food.routes.ts: -------------------------------------------------------------------------------- 1 | import { Routes } from '@angular/router'; 2 | import * as components from './container'; 3 | import * as fromFoodGuards from './guards'; 4 | 5 | export const FoodRoutes: Routes = [ 6 | { 7 | path: '', 8 | component: components.MainFoodComponent, 9 | }, 10 | { 11 | path: ':foodId', 12 | component: components.FoodDetailsComponent, 13 | canActivate: [fromFoodGuards.FoodIsLoadedGuard], 14 | }, 15 | ]; 16 | -------------------------------------------------------------------------------- /client/src/app/food/guards/food-is-loaded.guard.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { CanActivate } from '@angular/router'; 3 | import { Observable, of } from 'rxjs'; 4 | import { catchError, filter, switchMap, take, tap } from 'rxjs/operators'; 5 | import { FoodStoreFacade } from '../store/food-store.facade'; 6 | 7 | @Injectable({ providedIn: 'root' }) 8 | export class FoodIsLoadedGuard implements CanActivate { 9 | constructor(private facade: FoodStoreFacade) {} 10 | 11 | canActivate(): Observable { 12 | return this.checkStore().pipe( 13 | switchMap(() => of(true)), 14 | catchError(() => of(false)) 15 | ); 16 | } 17 | 18 | checkStore(): Observable { 19 | return this.facade.foodItemsLoaded$.pipe( 20 | tap(loaded => { 21 | if (!loaded) { 22 | this.facade.loadAllFoods(); 23 | } 24 | }), 25 | filter(loaded => loaded), 26 | take(1) 27 | ); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /client/src/app/food/guards/index.ts: -------------------------------------------------------------------------------- 1 | import { FoodIsLoadedGuard } from './food-is-loaded.guard'; 2 | 3 | export const foodGuards: any[] = [FoodIsLoadedGuard]; 4 | 5 | export * from './food-is-loaded.guard'; 6 | -------------------------------------------------------------------------------- /client/src/app/food/pipes/filter.pipe.spec.ts: -------------------------------------------------------------------------------- 1 | import { FilterPipe } from './filter.pipe'; 2 | 3 | describe('FilterPipe', () => { 4 | let filterPipe: FilterPipe; 5 | 6 | // synchronous beforeEach 7 | beforeEach(() => { 8 | filterPipe = new FilterPipe(); 9 | }); 10 | 11 | it('filterPipe should be instanciated', () => { 12 | expect(filterPipe).toBeDefined(); 13 | }); 14 | 15 | it('filterPipe should filter', () => { 16 | const items = []; 17 | 18 | items.push({ id: 1, name: 'Hans' }); 19 | items.push({ id: 2, name: 'Franz' }); 20 | items.push({ id: 3, name: 'Kurt' }); 21 | items.push({ id: 4, name: 'Gustav' }); 22 | 23 | const filtered = filterPipe.transform(items, 'name', 'Hans'); 24 | 25 | expect(filtered.length).toBeGreaterThan(0); 26 | expect(filtered.length).toBe(1); 27 | }); 28 | 29 | it('filterPipe should filter two items', () => { 30 | const items = []; 31 | 32 | items.push({ id: 1, name: 'Hans' }); 33 | items.push({ id: 2, name: 'Hans' }); 34 | items.push({ id: 3, name: 'Kurt' }); 35 | items.push({ id: 4, name: 'Gustav' }); 36 | 37 | const filtered = filterPipe.transform(items, 'name', 'Hans'); 38 | 39 | expect(filtered.length).toBe(2); 40 | }); 41 | }); 42 | -------------------------------------------------------------------------------- /client/src/app/food/pipes/filter.pipe.ts: -------------------------------------------------------------------------------- 1 | import { Injectable, Pipe, PipeTransform } from '@angular/core'; 2 | 3 | @Pipe({ 4 | name: 'filter', 5 | }) 6 | @Injectable() 7 | export class FilterPipe implements PipeTransform { 8 | transform(items: any[], field: string, value: string): any[] { 9 | if (!items) { 10 | return []; 11 | } 12 | if (!field || !value) { 13 | return items; 14 | } 15 | 16 | return items.filter(singleItem => 17 | singleItem[field].toLowerCase().includes(value.toLowerCase()) 18 | ); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /client/src/app/food/presentational/food-form/food-form.component.html: -------------------------------------------------------------------------------- 1 |
2 |
3 |
4 |
11 | 12 | 22 | 23 | * 31 |
32 | 33 |
40 | 41 | 51 |
52 | 53 |
60 | 61 | 75 | 76 | 82 | * 83 | 84 | 85 | 91 | Please enter a number 92 | 93 | 94 | 100 | Please enter a valid number (Integer-Range) 101 | 102 |
103 | 106 |
107 |
108 |
109 | -------------------------------------------------------------------------------- /client/src/app/food/presentational/food-form/food-form.component.ts: -------------------------------------------------------------------------------- 1 | import { 2 | Component, 3 | EventEmitter, 4 | Input, 5 | OnChanges, 6 | Output, 7 | SimpleChanges, 8 | } from '@angular/core'; 9 | import { FoodItem } from '../../../shared/models/foodItem.model'; 10 | 11 | @Component({ 12 | selector: 'app-food-form', 13 | templateUrl: './food-form.component.html', 14 | }) 15 | export class FoodFormComponent implements OnChanges { 16 | types: string[] = ['Starter', 'Main', 'Dessert']; 17 | @Input() 18 | foodItem: FoodItem; 19 | @Output() 20 | foodUpdated = new EventEmitter(); 21 | @Output() 22 | foodAdded = new EventEmitter(); 23 | 24 | currentFood: FoodItem = new FoodItem(); 25 | 26 | addOrUpdateFood() { 27 | !!this.foodItem 28 | ? this.foodUpdated.emit(this.currentFood) 29 | : this.foodAdded.emit(this.currentFood); 30 | } 31 | 32 | ngOnChanges(changes: SimpleChanges): void { 33 | this.currentFood = { ...changes.foodItem.currentValue }; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /client/src/app/food/presentational/food-list/food-list.component.css: -------------------------------------------------------------------------------- 1 | .margin-right { 2 | margin-right: 10px; 3 | } 4 | -------------------------------------------------------------------------------- /client/src/app/food/presentational/food-list/food-list.component.html: -------------------------------------------------------------------------------- 1 |
2 |
3 |
4 | 7 |
8 |
9 |
10 | 11 |
12 |
13 | 20 |
21 |
22 |
23 |
24 | 25 | 26 | 27 | 28 | 31 | 34 | 37 | 38 | 39 | 40 | 41 | 42 | 45 | 46 | 47 | 81 | 82 | 83 |
29 | Name 30 | 32 | Calories 33 | 35 | Type 36 | Actions
43 | {{ food.name }} 44 | {{ food.calories }}{{ food.type }} 48 | 80 |
84 | 85 | 86 | 127 | -------------------------------------------------------------------------------- /client/src/app/food/presentational/food-list/food-list.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, EventEmitter, Input, Output } from '@angular/core'; 2 | import { Sorter } from '@app/core/services/sort.service'; 3 | import { FoodItem } from '@app/shared/models/foodItem.model'; 4 | 5 | @Component({ 6 | selector: 'app-foodlist', 7 | templateUrl: './food-list.component.html', 8 | styleUrls: ['./food-list.component.css'], 9 | }) 10 | export class FoodListComponent { 11 | foodItem: FoodItem; 12 | foodToDelete: FoodItem; 13 | searchString: string; 14 | 15 | @Input() foods: FoodItem[]; 16 | @Output() foodSelected = new EventEmitter(); 17 | @Output() foodDeleted = new EventEmitter(); 18 | 19 | constructor(private sorter: Sorter) {} 20 | 21 | setFoodToDelete(foodItem: FoodItem): void { 22 | this.foodToDelete = foodItem; 23 | } 24 | 25 | sortArray(key: string, $event: any) { 26 | if ($event) { 27 | $event.preventDefault(); 28 | } 29 | this.sorter.sort(key, this.foods); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /client/src/app/food/presentational/food-picture/food-picture.component.css: -------------------------------------------------------------------------------- 1 | .img-responsive { 2 | width: 100%; 3 | height: auto; 4 | } 5 | -------------------------------------------------------------------------------- /client/src/app/food/presentational/food-picture/food-picture.component.html: -------------------------------------------------------------------------------- 1 | imagestring 8 | imagestring 15 | -------------------------------------------------------------------------------- /client/src/app/food/presentational/food-picture/food-picture.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { async, ComponentFixture, TestBed } from '@angular/core/testing'; 2 | import { AbstractCameraService } from '../../../core/services/abstract-camera.service'; 3 | import { MobileCameraService } from '../../../core/services/mobile-camera.service'; 4 | import { FoodPictureComponent } from './food-picture.component'; 5 | 6 | describe('FoodPictureComponent', () => { 7 | let component: FoodPictureComponent; 8 | let fixture: ComponentFixture; 9 | 10 | beforeEach(async(() => { 11 | TestBed.configureTestingModule({ 12 | declarations: [FoodPictureComponent], 13 | providers: [ 14 | { provide: AbstractCameraService, useClass: MobileCameraService }, 15 | ], 16 | }).compileComponents(); 17 | })); 18 | 19 | beforeEach(() => { 20 | fixture = TestBed.createComponent(FoodPictureComponent); 21 | component = fixture.componentInstance; 22 | }); 23 | 24 | it('should create', () => { 25 | fixture.detectChanges(); 26 | expect(component).toBeTruthy(); 27 | }); 28 | }); 29 | -------------------------------------------------------------------------------- /client/src/app/food/presentational/food-picture/food-picture.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, Input, NgZone } from '@angular/core'; 2 | import { AbstractCameraService } from '../../../core/services/abstract-camera.service'; 3 | import { FoodItem } from '../../../shared/models/foodItem.model'; 4 | 5 | @Component({ 6 | selector: 'app-food-picture', 7 | templateUrl: './food-picture.component.html', 8 | styleUrls: ['./food-picture.component.css'] 9 | }) 10 | export class FoodPictureComponent { 11 | @Input() foodItem: FoodItem; 12 | 13 | constructor( 14 | private cameraService: AbstractCameraService, 15 | private ngZone: NgZone 16 | ) {} 17 | 18 | takePicture($event: any, foodItem: FoodItem) { 19 | $event.preventDefault(); 20 | this.cameraService.getPhoto().subscribe((imageString: string) => { 21 | this.ngZone.run(() => { 22 | foodItem.imageString = imageString; 23 | }); 24 | }); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /client/src/app/food/presentational/index.ts: -------------------------------------------------------------------------------- 1 | import { FoodFormComponent } from './food-form/food-form.component'; 2 | import { FoodListComponent } from './food-list/food-list.component'; 3 | import { FoodPictureComponent } from './food-picture/food-picture.component'; 4 | import { IngredientListComponent } from './ingredient-list/ingredient-list.component'; 5 | 6 | export const allPresComponents: any[] = [ 7 | FoodFormComponent, 8 | FoodListComponent, 9 | FoodPictureComponent, 10 | IngredientListComponent, 11 | ]; 12 | -------------------------------------------------------------------------------- /client/src/app/food/presentational/ingredient-list/ingredient-list.component.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FabianGosebrink/ASPNETCore-Angular-Ngrx/8c697557c83d8375a1ea06ab5fdfd19348e29204/client/src/app/food/presentational/ingredient-list/ingredient-list.component.css -------------------------------------------------------------------------------- /client/src/app/food/presentational/ingredient-list/ingredient-list.component.html: -------------------------------------------------------------------------------- 1 | 11 | -------------------------------------------------------------------------------- /client/src/app/food/presentational/ingredient-list/ingredient-list.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { async, ComponentFixture, TestBed } from '@angular/core/testing'; 2 | 3 | import { IngredientListComponent } from './ingredient-list.component'; 4 | 5 | describe('IngredientListComponent', () => { 6 | let component: IngredientListComponent; 7 | let fixture: ComponentFixture; 8 | 9 | beforeEach(async(() => { 10 | TestBed.configureTestingModule({ 11 | declarations: [ IngredientListComponent ] 12 | }) 13 | .compileComponents(); 14 | })); 15 | 16 | beforeEach(() => { 17 | fixture = TestBed.createComponent(IngredientListComponent); 18 | component = fixture.componentInstance; 19 | fixture.detectChanges(); 20 | }); 21 | 22 | it('should create', () => { 23 | expect(component).toBeTruthy(); 24 | }); 25 | }); 26 | -------------------------------------------------------------------------------- /client/src/app/food/presentational/ingredient-list/ingredient-list.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core'; 2 | import { Ingredient } from '../../../shared/models/ingredient.model'; 3 | 4 | @Component({ 5 | selector: 'app-ingredient-list', 6 | templateUrl: './ingredient-list.component.html', 7 | styleUrls: ['./ingredient-list.component.css'], 8 | }) 9 | export class IngredientListComponent implements OnInit { 10 | @Input() 11 | ingredients: Ingredient[]; 12 | 13 | @Output() 14 | ingredientDeleted = new EventEmitter(); 15 | constructor() {} 16 | 17 | ngOnInit() {} 18 | 19 | delete(ingredient: Ingredient) { 20 | this.ingredientDeleted.emit(ingredient); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /client/src/app/food/store/actions/food.actions.ts: -------------------------------------------------------------------------------- 1 | import { createAction, props } from '@ngrx/store'; 2 | import { FoodItem } from '@app/shared/models/foodItem.model'; 3 | import { ModelDescriptor } from '@app/shared/models/model.descriptor'; 4 | 5 | export const addFood = createAction( 6 | '[Foods] ADD_FOOD', 7 | props<{ payload: FoodItem }>() 8 | ); 9 | 10 | export const addFoodSuccess = createAction( 11 | '[Foods] ADD_FOOD_SUCCESS', 12 | props<{ payload: FoodItem }>() 13 | ); 14 | 15 | export const loadFood = createAction('[Foods] LOAD_FOOD'); 16 | 17 | export const loadFoodSuccess = createAction( 18 | '[Foods] LOAD_FOOD_SUCCESS', 19 | props<{ payload: ModelDescriptor }>() 20 | ); 21 | 22 | export const deleteFood = createAction( 23 | '[Foods] DELETE_FOOD', 24 | props<{ payload: FoodItem }>() 25 | ); 26 | 27 | export const deleteFoodSuccess = createAction( 28 | '[Foods] DELETE_FOOD_SUCCESS', 29 | props<{ payload: any }>() 30 | ); 31 | 32 | export const updateFood = createAction( 33 | '[Foods] UPDATE_FOOD', 34 | props<{ payload: FoodItem }>() 35 | ); 36 | 37 | export const updateFoodSuccess = createAction( 38 | '[Foods] UPDATE_FOOD_SUCCESS', 39 | props<{ payload: FoodItem }>() 40 | ); 41 | 42 | export const foodError = createAction( 43 | '[Foods] FOOD_ERROR', 44 | props<{ payload: any }>() 45 | ); 46 | -------------------------------------------------------------------------------- /client/src/app/food/store/actions/index.ts: -------------------------------------------------------------------------------- 1 | export * from './food.actions'; 2 | export * from './signalR.actions'; 3 | export * from './ingredients.actions'; 4 | -------------------------------------------------------------------------------- /client/src/app/food/store/actions/ingredients.actions.ts: -------------------------------------------------------------------------------- 1 | import { createAction, props } from '@ngrx/store'; 2 | import { Ingredient } from '@app/shared/models/ingredient.model'; 3 | 4 | export const loadIngredients = createAction( 5 | '[Foods] LOAD_INGREDIENTS', 6 | props<{ payload: string }>() 7 | ); 8 | 9 | export const loadIngredientsSuccess = createAction( 10 | '[Foods] LOAD_INGREDIENTS_SUCCESS', 11 | props<{ payload: Ingredient[] }>() 12 | ); 13 | 14 | export const deleteIngredient = createAction( 15 | '[Foods] DELETE_INGREDIENT', 16 | props<{ payload: Ingredient; foodId: string }>() 17 | ); 18 | 19 | export const deleteIngredientSuccess = createAction( 20 | '[Foods] DELETE_INGREDIENT_SUCCESS', 21 | props<{ payload: any }>() 22 | ); 23 | 24 | export const addIngredient = createAction( 25 | '[Foods] ADD_INGREDIENTS', 26 | props<{ payload: Ingredient; foodId: string }>() 27 | ); 28 | 29 | export const addIngredientSuccess = createAction( 30 | '[Foods] ADD_INGREDIENTS_SUCCESS', 31 | props<{ payload: Ingredient }>() 32 | ); 33 | 34 | export const ingredientError = createAction( 35 | '[Foods] INGREDIENTS_ERROR', 36 | props<{ payload: any }>() 37 | ); 38 | -------------------------------------------------------------------------------- /client/src/app/food/store/actions/signalR.actions.ts: -------------------------------------------------------------------------------- 1 | import { createAction, props } from '@ngrx/store'; 2 | import { FoodItem } from '@app/shared/models/foodItem.model'; 3 | import { Ingredient } from '@app/shared/models/ingredient.model'; 4 | 5 | export const receivedFoodAdded = createAction( 6 | '[SignalR] RECEIVED_FOOD_ADDED', 7 | props<{ payload: FoodItem }>() 8 | ); 9 | 10 | export const receivedIngredientAdded = createAction( 11 | '[SignalR] RECEIVED_INGREDIENT_ADDED', 12 | props<{ payload: Ingredient }>() 13 | ); 14 | 15 | export const receivedIngredientDeleted = createAction( 16 | '[SignalR] RECEIVED_INGREDIENT_DELETED', 17 | props<{ payload: string }>() 18 | ); 19 | 20 | export const receiveFoodUpdated = createAction( 21 | '[SignalR] RECEIVED_FOOD_UPDATED', 22 | props<{ payload: FoodItem }>() 23 | ); 24 | 25 | export const receiveFoodDeleted = createAction( 26 | '[SignalR] RECEIVED_FOOD_DELETED', 27 | props<{ payload: string }>() 28 | ); 29 | -------------------------------------------------------------------------------- /client/src/app/food/store/effects/food.effects.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { Actions, ofType, createEffect } from '@ngrx/effects'; 3 | import { of } from 'rxjs'; 4 | import { catchError, map, switchMap, tap } from 'rxjs/operators'; 5 | import * as foodActions from '../actions/food.actions'; 6 | import { FoodDataService } from '@app/core/data-services/food-data.service'; 7 | import { AbstractNotificationService } from '@app/core/services/abstract-notification.service'; 8 | 9 | @Injectable() 10 | export class FoodEffects { 11 | addFood$ = createEffect(() => 12 | this.actions$.pipe( 13 | ofType(foodActions.addFood), 14 | switchMap(({ payload }) => 15 | this.foodDataService.addFood(payload).pipe( 16 | map(data => foodActions.addFoodSuccess({ payload: data })), 17 | catchError(error => of(foodActions.foodError({ payload: error }))) 18 | ) 19 | ) 20 | ) 21 | ); 22 | 23 | loadFood$ = createEffect(() => 24 | this.actions$.pipe( 25 | ofType(foodActions.loadFood), 26 | switchMap(action => 27 | this.foodDataService.getAllFood().pipe( 28 | map(data => foodActions.loadFoodSuccess({ payload: data })), 29 | catchError(error => of(foodActions.foodError({ payload: error }))) 30 | ) 31 | ) 32 | ) 33 | ); 34 | 35 | deleteFood$ = createEffect(() => 36 | this.actions$.pipe( 37 | ofType(foodActions.deleteFood), 38 | switchMap(({ payload }) => 39 | this.foodDataService.deleteFood(payload).pipe( 40 | map(() => { 41 | this.notificationService.showSuccess('Food', 'Food deleted!'); 42 | return foodActions.deleteFoodSuccess({ payload }); 43 | }), 44 | catchError(error => of(foodActions.foodError({ payload: error }))) 45 | ) 46 | ) 47 | ) 48 | ); 49 | 50 | updateFood$ = createEffect(() => 51 | this.actions$.pipe( 52 | ofType(foodActions.updateFood), 53 | switchMap(({ payload }) => 54 | this.foodDataService.updateFood(payload.id, payload).pipe( 55 | map(data => { 56 | this.notificationService.showSuccess('Food', 'Food updated!'); 57 | return foodActions.updateFoodSuccess({ payload: data }); 58 | }), 59 | catchError(error => of(foodActions.foodError({ payload: error }))) 60 | ) 61 | ) 62 | ) 63 | ); 64 | 65 | foodError$ = createEffect( 66 | () => 67 | this.actions$.pipe( 68 | ofType(foodActions.foodError), 69 | tap(({ payload }) => 70 | this.notificationService.showError('Food', payload.error.statusText) 71 | ) 72 | ), 73 | { dispatch: false } 74 | ); 75 | 76 | constructor( 77 | private foodDataService: FoodDataService, 78 | private notificationService: AbstractNotificationService, 79 | private actions$: Actions 80 | ) {} 81 | } 82 | -------------------------------------------------------------------------------- /client/src/app/food/store/effects/index.ts: -------------------------------------------------------------------------------- 1 | import { FoodEffects } from './food.effects'; 2 | import { IngredientEffects } from './ingredients.effects'; 3 | 4 | export const effects: any[] = [FoodEffects, IngredientEffects]; 5 | 6 | export * from './food.effects'; 7 | export * from './ingredients.effects'; 8 | -------------------------------------------------------------------------------- /client/src/app/food/store/effects/ingredients.effects.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { Actions, ofType, createEffect } from '@ngrx/effects'; 3 | import { of } from 'rxjs'; 4 | import { catchError, map, switchMap, tap } from 'rxjs/operators'; 5 | import { IngredientsDataService } from '@app/core/data-services/ingredient-data.service'; 6 | import { AbstractNotificationService } from '@app/core/services/abstract-notification.service'; 7 | import * as ingredientActions from '../actions/ingredients.actions'; 8 | 9 | @Injectable() 10 | export class IngredientEffects { 11 | addIngredient$ = createEffect(() => 12 | this.actions$.pipe( 13 | ofType(ingredientActions.addIngredient), 14 | switchMap(({ payload, foodId }) => 15 | this.ingredientsDataService.add(payload, foodId).pipe( 16 | map(data => 17 | ingredientActions.addIngredientSuccess({ payload: data }) 18 | ), 19 | catchError(error => 20 | of(ingredientActions.ingredientError({ payload: error })) 21 | ) 22 | ) 23 | ) 24 | ) 25 | ); 26 | 27 | loadIngredients$ = createEffect(() => 28 | this.actions$.pipe( 29 | ofType(ingredientActions.loadIngredients), 30 | switchMap(({ payload }) => 31 | this.ingredientsDataService.getIngredientsForFood(payload).pipe( 32 | map(data => 33 | ingredientActions.loadIngredientsSuccess({ payload: data }) 34 | ), 35 | catchError(error => 36 | of(ingredientActions.ingredientError({ payload: error })) 37 | ) 38 | ) 39 | ) 40 | ) 41 | ); 42 | 43 | deleteIngredient$ = createEffect(() => 44 | this.actions$.pipe( 45 | ofType(ingredientActions.deleteIngredient), 46 | switchMap(({ payload, foodId }) => 47 | this.ingredientsDataService.delete(payload, foodId).pipe( 48 | map(() => { 49 | this.notificationService.showSuccess( 50 | 'Ingredients', 51 | 'Ingredient deleted!' 52 | ); 53 | return ingredientActions.deleteIngredientSuccess({ payload }); 54 | }), 55 | catchError(error => 56 | of(ingredientActions.ingredientError({ payload: error })) 57 | ) 58 | ) 59 | ) 60 | ) 61 | ); 62 | 63 | ingredientError$ = createEffect( 64 | () => 65 | this.actions$.pipe( 66 | ofType(ingredientActions.ingredientError), 67 | tap(({ payload }) => 68 | this.notificationService.showError( 69 | 'Ingredients', 70 | payload.error.statusText 71 | ) 72 | ) 73 | ), 74 | { dispatch: false } 75 | ); 76 | 77 | constructor( 78 | private ingredientsDataService: IngredientsDataService, 79 | private notificationService: AbstractNotificationService, 80 | private actions$: Actions 81 | ) {} 82 | } 83 | -------------------------------------------------------------------------------- /client/src/app/food/store/food-store.facade.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { select, Store } from '@ngrx/store'; 3 | import { FoodItem } from '../../shared/models/foodItem.model'; 4 | import { Ingredient } from '../../shared/models/ingredient.model'; 5 | import * as fromActions from './actions'; 6 | import * as fromReducers from './reducers'; 7 | import * as fromSelectors from './selectors'; 8 | 9 | @Injectable({ providedIn: 'root' }) 10 | export class FoodStoreFacade { 11 | foodItemsLoaded$ = this.store.pipe(select(fromSelectors.getFoodItemsLoaded)); 12 | allFoods$ = this.store.pipe(select(fromSelectors.getAllFoods)); 13 | selectedFood$ = this.store.pipe(select(fromSelectors.getSelectedFood)); 14 | ingredients$ = this.store.pipe(select(fromSelectors.getAllIngredients)); 15 | 16 | constructor(private store: Store) {} 17 | 18 | loadAllFoods() { 19 | this.store.dispatch(fromActions.loadFood()); 20 | } 21 | 22 | loadAllIngredients(payload: string) { 23 | this.store.dispatch(fromActions.loadIngredients({ payload })); 24 | } 25 | 26 | addFood(payload: FoodItem) { 27 | this.store.dispatch(fromActions.addFood({ payload })); 28 | } 29 | 30 | addIngredient(ingredient: Ingredient, foodId: string) { 31 | this.store.dispatch( 32 | fromActions.addIngredient({ payload: ingredient, foodId }) 33 | ); 34 | } 35 | 36 | updateFood(payload: FoodItem) { 37 | this.store.dispatch(fromActions.updateFood({ payload })); 38 | } 39 | 40 | deleteFood(payload: FoodItem) { 41 | this.store.dispatch(fromActions.deleteFood({ payload })); 42 | } 43 | 44 | deleteIngredient(ingredient: Ingredient, foodId: string) { 45 | this.store.dispatch( 46 | fromActions.deleteIngredient({ payload: ingredient, foodId }) 47 | ); 48 | } 49 | 50 | receivedFoodData(data: any) { 51 | this.store.dispatch(fromActions.receivedFoodAdded({ payload: data })); 52 | } 53 | 54 | receivedFoodDeleted(data: any) { 55 | this.store.dispatch(fromActions.receiveFoodDeleted({ payload: data })); 56 | } 57 | 58 | receivedFoodUpdated(data: any) { 59 | this.store.dispatch(fromActions.receiveFoodUpdated({ payload: data })); 60 | } 61 | 62 | receivedIngredientAdded(payload: Ingredient) { 63 | this.store.dispatch(fromActions.receivedIngredientAdded({ payload })); 64 | } 65 | 66 | receivedIngredientDeleted(payload: string) { 67 | this.store.dispatch(fromActions.receivedIngredientDeleted({ payload })); 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /client/src/app/food/store/reducers/food.reducer.spec.ts: -------------------------------------------------------------------------------- 1 | import { FoodItem } from '../../../shared/models/foodItem.model'; 2 | import { addFood } from '../actions'; 3 | import { foodReducer, FoodReducerState } from './food.reducer'; 4 | 5 | describe('FoodList', () => { 6 | it('should return an array with the new food added to it', () => { 7 | const initialState: FoodReducerState = { 8 | entities: { ['A']: new FoodItem(), ['B']: new FoodItem() }, 9 | loaded: false, 10 | loading: false 11 | }; 12 | 13 | const foodItemToAdd = new FoodItem(); 14 | 15 | foodItemToAdd.id = 'test'; 16 | 17 | const newState = foodReducer( 18 | initialState, 19 | addFood({ payload: foodItemToAdd }) 20 | ); 21 | 22 | expect(newState.entities['test']).toBeDefined(); 23 | }); 24 | }); 25 | -------------------------------------------------------------------------------- /client/src/app/food/store/reducers/food.reducer.ts: -------------------------------------------------------------------------------- 1 | import { FoodItem } from '../../../shared/models/foodItem.model'; 2 | import * as foodActions from '../actions/food.actions'; 3 | import * as signalrActions from '../actions/signalR.actions'; 4 | import { Action, createReducer, on } from '@ngrx/store'; 5 | 6 | export interface FoodReducerState { 7 | entities: { [id: string]: FoodItem }; 8 | loaded: boolean; 9 | loading: boolean; 10 | } 11 | 12 | export const initialState: FoodReducerState = { 13 | entities: {}, 14 | loaded: false, 15 | loading: false 16 | }; 17 | 18 | const foodReducerInternal = createReducer( 19 | initialState, 20 | on( 21 | foodActions.addFoodSuccess, 22 | foodActions.updateFoodSuccess, 23 | (state, { payload }) => { 24 | const entities = { 25 | ...state.entities, 26 | [payload.id]: payload 27 | }; 28 | 29 | return { 30 | ...state, 31 | entities 32 | }; 33 | } 34 | ), 35 | on(foodActions.loadFoodSuccess, (state, { payload }) => { 36 | const entities: { [id: string]: FoodItem } = {}; 37 | 38 | for (const entity of payload.value) { 39 | entities[entity.id] = entity; 40 | } 41 | 42 | return { 43 | ...state, 44 | entities, 45 | loaded: true 46 | }; 47 | }), 48 | 49 | on(foodActions.deleteFoodSuccess, (state, { payload }) => { 50 | const foodItem = payload; 51 | const { [foodItem.id]: removed, ...entities } = state.entities; 52 | 53 | return { 54 | ...state, 55 | entities 56 | }; 57 | }), 58 | 59 | on(signalrActions.receivedFoodAdded, (state, { payload }) => { 60 | if (!!state.entities[payload.id]) { 61 | return state; 62 | } 63 | 64 | const foodItem = payload; 65 | const entities = { 66 | ...state.entities, 67 | [foodItem.id]: foodItem 68 | }; 69 | 70 | return { 71 | ...state, 72 | entities 73 | }; 74 | }), 75 | 76 | on(signalrActions.receiveFoodDeleted, (state, { payload }) => { 77 | if (!state.entities[payload]) { 78 | return state; 79 | } 80 | 81 | const { [payload]: removed, ...entities } = state.entities; 82 | 83 | return { 84 | ...state, 85 | entities 86 | }; 87 | }), 88 | 89 | on(signalrActions.receiveFoodUpdated, (state, { payload }) => { 90 | const foodItem = payload; 91 | 92 | const entities = { 93 | ...state.entities, 94 | [foodItem.id]: foodItem 95 | }; 96 | 97 | return { 98 | ...state, 99 | entities 100 | }; 101 | }) 102 | ); 103 | 104 | export function foodReducer( 105 | state: FoodReducerState | undefined, 106 | action: Action 107 | ) { 108 | return foodReducerInternal(state, action); 109 | } 110 | 111 | export const getFoodItemEntities = (state: FoodReducerState) => state.entities; 112 | export const getFoodItemsLoaded = (state: FoodReducerState) => state.loaded; 113 | export const getFoodItemsLoading = (state: FoodReducerState) => state.loading; 114 | -------------------------------------------------------------------------------- /client/src/app/food/store/reducers/index.ts: -------------------------------------------------------------------------------- 1 | import { ActionReducerMap, createFeatureSelector } from '@ngrx/store'; 2 | import * as fromFood from './food.reducer'; 3 | import * as fromIngredients from './ingredient.reducer'; 4 | 5 | export interface FoodState { 6 | foods: fromFood.FoodReducerState; 7 | ingredients: fromIngredients.IngredientReducerState; 8 | } 9 | 10 | export const reducers: ActionReducerMap = { 11 | foods: fromFood.foodReducer, 12 | ingredients: fromIngredients.ingredientReducer 13 | }; 14 | 15 | export const getFoodState = createFeatureSelector('food'); 16 | -------------------------------------------------------------------------------- /client/src/app/food/store/reducers/ingredient.reducer.ts: -------------------------------------------------------------------------------- 1 | import { Ingredient } from '../../../shared/models/ingredient.model'; 2 | import * as ingredientActions from '../actions/ingredients.actions'; 3 | import * as signalrActions from '../actions/signalR.actions'; 4 | import { Action, createReducer, on } from '@ngrx/store'; 5 | 6 | export interface IngredientReducerState { 7 | entities: { [id: string]: Ingredient }; 8 | loaded: boolean; 9 | loading: boolean; 10 | } 11 | 12 | export const initialState: IngredientReducerState = { 13 | entities: {}, 14 | loaded: false, 15 | loading: false 16 | }; 17 | 18 | const ingredientsReducerinternal = createReducer( 19 | initialState, 20 | on(signalrActions.receivedIngredientAdded, (state, { payload }) => { 21 | if (!!state.entities[payload.id]) { 22 | return state; 23 | } 24 | 25 | const ingredient = payload; 26 | const entities = { 27 | ...state.entities, 28 | [ingredient.id]: ingredient 29 | }; 30 | 31 | return { 32 | ...state, 33 | entities 34 | }; 35 | }), 36 | 37 | on(signalrActions.receivedIngredientDeleted, (state, { payload }) => { 38 | if (!state.entities[payload]) { 39 | return state; 40 | } 41 | 42 | const { [payload]: removed, ...entities } = state.entities; 43 | 44 | return { 45 | ...state, 46 | entities 47 | }; 48 | }), 49 | 50 | on(ingredientActions.addIngredientSuccess, (state, { payload }) => { 51 | const ingredient = payload; 52 | 53 | const entities = { 54 | ...state.entities, 55 | [ingredient.id]: ingredient 56 | }; 57 | 58 | return { 59 | ...state, 60 | entities 61 | }; 62 | }), 63 | 64 | on(ingredientActions.deleteIngredientSuccess, (state, { payload }) => { 65 | const ingredient = payload; 66 | const { [ingredient.id]: removed, ...entities } = state.entities; 67 | 68 | return { 69 | ...state, 70 | entities 71 | }; 72 | }), 73 | 74 | on(ingredientActions.loadIngredientsSuccess, (state, { payload }) => { 75 | const entities: { [id: string]: Ingredient } = {}; 76 | 77 | for (const entity of payload) { 78 | entities[entity.id] = entity; 79 | } 80 | return { 81 | ...state, 82 | entities, 83 | loaded: true 84 | }; 85 | }) 86 | ); 87 | 88 | export const getIngredientItemEntities = (state: IngredientReducerState) => 89 | state.entities; 90 | export const getIngredientsLoaded = (state: IngredientReducerState) => 91 | state.loaded; 92 | export const getIngredientsLoading = (state: IngredientReducerState) => 93 | state.loading; 94 | 95 | export function ingredientReducer( 96 | state: IngredientReducerState | undefined, 97 | action: Action 98 | ) { 99 | return ingredientsReducerinternal(state, action); 100 | } 101 | -------------------------------------------------------------------------------- /client/src/app/food/store/selectors/foods.selectors.ts: -------------------------------------------------------------------------------- 1 | import { createSelector } from '@ngrx/store'; 2 | import * as fromAppRoot from '../../../store'; 3 | import * as fromFeature from '../reducers'; 4 | import * as fromFood from '../reducers/food.reducer'; 5 | import { FoodItem } from '@app/shared/models/foodItem.model'; 6 | 7 | export const getCompleteFoodState = createSelector( 8 | fromFeature.getFoodState, 9 | (state: fromFeature.FoodState) => state.foods 10 | ); 11 | 12 | export const getAllFoodEntities = createSelector( 13 | getCompleteFoodState, 14 | fromFood.getFoodItemEntities 15 | ); 16 | 17 | export const getFoodItemsLoaded = createSelector( 18 | getCompleteFoodState, 19 | fromFood.getFoodItemsLoaded 20 | ); 21 | 22 | export const getAllFoods = createSelector( 23 | getAllFoodEntities, 24 | entities => { 25 | return Object.keys(entities).map(id => entities[id]); 26 | } 27 | ); 28 | 29 | export const getSelectedFood = createSelector( 30 | getAllFoodEntities, 31 | fromAppRoot.getRouterState, 32 | (entities, router): FoodItem => { 33 | return router.state && entities[router.state.params.foodId]; 34 | } 35 | ); 36 | -------------------------------------------------------------------------------- /client/src/app/food/store/selectors/index.ts: -------------------------------------------------------------------------------- 1 | export * from './foods.selectors'; 2 | export * from './ingredients.selectors'; 3 | -------------------------------------------------------------------------------- /client/src/app/food/store/selectors/ingredients.selectors.ts: -------------------------------------------------------------------------------- 1 | import { createSelector } from '@ngrx/store'; 2 | import * as fromFeature from '../reducers'; 3 | import * as fromIngredient from '../reducers/ingredient.reducer'; 4 | 5 | export const getCompleteIngredientState = createSelector( 6 | fromFeature.getFoodState, 7 | (state: fromFeature.FoodState) => state.ingredients 8 | ); 9 | 10 | export const getAllIngredientEntities = createSelector( 11 | getCompleteIngredientState, 12 | fromIngredient.getIngredientItemEntities 13 | ); 14 | 15 | export const getIngredientsLoaded = createSelector( 16 | getCompleteIngredientState, 17 | fromIngredient.getIngredientsLoaded 18 | ); 19 | 20 | export const getAllIngredients = createSelector( 21 | getAllIngredientEntities, 22 | entities => { 23 | return Object.keys(entities).map(id => entities[id]); 24 | } 25 | ); 26 | -------------------------------------------------------------------------------- /client/src/app/food/validators/isInRange.validator.ts: -------------------------------------------------------------------------------- 1 | import { Attribute, Directive, forwardRef } from '@angular/core'; 2 | import { 3 | FormControl, 4 | NG_VALIDATORS, 5 | ValidationErrors, 6 | Validator, 7 | } from '@angular/forms'; 8 | 9 | const INT_MAX = 2147483647; 10 | 11 | @Directive({ 12 | selector: 13 | '[app-isInRange][formControlName],[app-isInRange][formControl],[app-isInRange][ngModel]', 14 | providers: [ 15 | { 16 | provide: NG_VALIDATORS, 17 | useExisting: forwardRef(() => IsInRangeValidator), 18 | multi: true, 19 | }, 20 | ], 21 | }) 22 | export class IsInRangeValidator implements Validator { 23 | private _minValue: number; 24 | private _maxValue: number; 25 | 26 | constructor( 27 | @Attribute('minValue') minValue: number, 28 | @Attribute('maxValue') maxValue: number 29 | ) { 30 | this._minValue = minValue || 0; 31 | this._maxValue = maxValue || INT_MAX; 32 | } 33 | 34 | validate(c: FormControl): ValidationErrors | null { 35 | if (+c.value > this._maxValue || +c.value < this._minValue) { 36 | return { 37 | isInRange: { 38 | valid: false, 39 | }, 40 | }; 41 | } 42 | 43 | return null; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /client/src/app/food/validators/isInRangeValidator.spec.ts: -------------------------------------------------------------------------------- 1 | import { FormControl } from '@angular/forms'; 2 | import { IsInRangeValidator } from './isInRange.validator'; 3 | 4 | const INT_MAX = 2147483647; 5 | 6 | describe('IsInRange', () => { 7 | let isInRangeValidator: IsInRangeValidator; 8 | 9 | // synchronous beforeEach 10 | beforeEach(() => { 11 | isInRangeValidator = new IsInRangeValidator(0, INT_MAX); 12 | }); 13 | 14 | it('isInRangeValidator should be instanciated', () => { 15 | expect(isInRangeValidator).toBeDefined(); 16 | }); 17 | 18 | it('isInRangeValidator should be valid', () => { 19 | const formcontrol = new FormControl(); 20 | formcontrol.setValue(123); 21 | const result = isInRangeValidator.validate(formcontrol); 22 | 23 | expect(result).toBeNull(); 24 | }); 25 | 26 | it('isInRangeValidator should be invalid on higher number', () => { 27 | const formcontrol = new FormControl(); 28 | formcontrol.setValue(2147483648); 29 | const result = isInRangeValidator.validate(formcontrol); 30 | 31 | expect(result).not.toBeNull(); 32 | expect(result['isInRange']).not.toBeNull(); 33 | expect(result['isInRange'].valid).toBeFalsy(); 34 | }); 35 | 36 | it('isInRangeValidator should be invalid on lower number', () => { 37 | const formcontrol = new FormControl(); 38 | formcontrol.setValue(-1); 39 | const result = isInRangeValidator.validate(formcontrol); 40 | 41 | expect(result).not.toBeNull(); 42 | expect(result['isInRange']).not.toBeNull(); 43 | expect(result['isInRange'].valid).toBeFalsy(); 44 | }); 45 | }); 46 | -------------------------------------------------------------------------------- /client/src/app/food/validators/isNumber.validator.spec.ts: -------------------------------------------------------------------------------- 1 | import { FormControl } from '@angular/forms'; 2 | import { IsNumberValidator } from './isNumber.validator'; 3 | 4 | const INT_MAX = 2147483647; 5 | 6 | describe('IsNumber', () => { 7 | let isNumberValidator: IsNumberValidator; 8 | 9 | // synchronous beforeEach 10 | beforeEach(() => { 11 | isNumberValidator = new IsNumberValidator(); 12 | }); 13 | 14 | it('validator should be instanciated', () => { 15 | expect(isNumberValidator).toBeDefined(); 16 | }); 17 | 18 | it('validator should be valid when number is passed', () => { 19 | const formcontrol = new FormControl(); 20 | formcontrol.setValue(123); 21 | const result = isNumberValidator.validate(formcontrol); 22 | 23 | expect(result).toBeNull(); 24 | }); 25 | 26 | it('validator should be invalid when character is passed', () => { 27 | const formcontrol = new FormControl(); 28 | formcontrol.setValue('s'); 29 | const result = isNumberValidator.validate(formcontrol); 30 | 31 | expect(result).not.toBeNull(); 32 | expect(result['isNumber']).not.toBeNull(); 33 | expect(result['isNumber'].valid).toBeFalsy(); 34 | }); 35 | }); 36 | -------------------------------------------------------------------------------- /client/src/app/food/validators/isNumber.validator.ts: -------------------------------------------------------------------------------- 1 | import { Directive, forwardRef } from '@angular/core'; 2 | import { 3 | FormControl, 4 | NG_VALIDATORS, 5 | ValidationErrors, 6 | Validator, 7 | } from '@angular/forms'; 8 | 9 | @Directive({ 10 | selector: 11 | '[app-isNumber][formControlName],[app-isNumber][formControl],[app-isNumber][ngModel]', 12 | providers: [ 13 | { 14 | provide: NG_VALIDATORS, 15 | useExisting: forwardRef(() => IsNumberValidator), 16 | multi: true, 17 | }, 18 | ], 19 | }) 20 | export class IsNumberValidator implements Validator { 21 | validate(c: FormControl): ValidationErrors | null { 22 | if (isNaN(+c.value)) { 23 | return { 24 | isNumber: { 25 | valid: false, 26 | }, 27 | }; 28 | } 29 | 30 | return null; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /client/src/app/home/home.module.ts: -------------------------------------------------------------------------------- 1 | import { CommonModule } from '@angular/common'; 2 | import { HttpClientModule } from '@angular/common/http'; 3 | import { NgModule } from '@angular/core'; 4 | import { FormsModule } from '@angular/forms'; 5 | import { RouterModule } from '@angular/router'; 6 | import { EffectsModule } from '@ngrx/effects'; 7 | import { StoreModule } from '@ngrx/store'; 8 | import { SharedModule } from '../shared/shared.module'; 9 | import { HomeRoutes } from './home.routes'; 10 | import { HomeComponent } from './home/home.component'; 11 | import { RandomMealComponent } from './randomMeal/randomMeal.component'; 12 | import { SingleMealComponent } from './single-meal/single-meal.component'; 13 | import { effects } from './store/effects'; 14 | import { reducers } from './store/reducers'; 15 | 16 | @NgModule({ 17 | imports: [ 18 | // Modules 19 | CommonModule, 20 | FormsModule, 21 | HttpClientModule, 22 | SharedModule, 23 | RouterModule.forChild(HomeRoutes), 24 | StoreModule.forFeature('home', reducers), 25 | EffectsModule.forFeature(effects), 26 | ], 27 | 28 | declarations: [ 29 | // Components & Directives 30 | HomeComponent, 31 | RandomMealComponent, 32 | SingleMealComponent, 33 | ], 34 | 35 | exports: [HomeComponent], 36 | }) 37 | export class HomeModule {} 38 | -------------------------------------------------------------------------------- /client/src/app/home/home.routes.ts: -------------------------------------------------------------------------------- 1 | import { Routes } from '@angular/router'; 2 | import { HomeComponent } from './home/home.component'; 3 | 4 | export const HomeRoutes: Routes = [{ path: 'home', component: HomeComponent }]; 5 | -------------------------------------------------------------------------------- /client/src/app/home/home/home.component.css: -------------------------------------------------------------------------------- 1 | .event-list { 2 | list-style: none; 3 | font-family: 'Lato', sans-serif; 4 | margin: 0px; 5 | padding: 0px; 6 | } 7 | 8 | .event-list>li { 9 | background-color: rgb(255, 255, 255); 10 | box-shadow: 0px 0px 5px rgb(51, 51, 51); 11 | box-shadow: 0px 0px 5px rgba(51, 51, 51, 0.7); 12 | padding: 0px; 13 | margin: 0px 0px 20px; 14 | } 15 | 16 | .event-list>li>time { 17 | display: inline-block; 18 | width: 100%; 19 | color: rgb(255, 255, 255); 20 | background-color: rgb(45, 137, 239); 21 | padding: 5px; 22 | text-align: center; 23 | text-transform: uppercase; 24 | } 25 | 26 | .event-list>li:nth-child(even)>time { 27 | background-color: rgb(153, 180, 51); 28 | } 29 | 30 | .event-list>li>time>span { 31 | display: none; 32 | } 33 | 34 | .event-list>li>time>.day { 35 | display: block; 36 | font-size: 56pt; 37 | font-weight: 100; 38 | line-height: 1; 39 | } 40 | 41 | .event-list>li time>.month { 42 | display: block; 43 | font-size: 24pt; 44 | font-weight: 900; 45 | line-height: 1; 46 | } 47 | 48 | .event-list>li>img { 49 | width: 100%; 50 | } 51 | 52 | .event-list>li>.info { 53 | padding-top: 5px; 54 | text-align: center; 55 | } 56 | 57 | .event-list>li>.info>.title { 58 | font-size: 17pt; 59 | font-weight: 700; 60 | margin: 0px; 61 | } 62 | 63 | .event-list>li>.info>.desc { 64 | font-size: 13pt; 65 | font-weight: 300; 66 | margin: 0px; 67 | } 68 | 69 | .event-list>li>.info>ul, 70 | .event-list>li>.social>ul { 71 | display: table; 72 | list-style: none; 73 | margin: 10px 0px 0px; 74 | padding: 0px; 75 | width: 100%; 76 | text-align: center; 77 | } 78 | 79 | .event-list>li>.social>ul { 80 | margin: 0px; 81 | } 82 | 83 | .event-list>li>.info>ul>li, 84 | .event-list>li>.social>ul>li { 85 | display: table-cell; 86 | cursor: pointer; 87 | color: rgb(30, 30, 30); 88 | font-size: 11pt; 89 | font-weight: 300; 90 | padding: 3px 0px; 91 | } 92 | 93 | .event-list>li>.info>ul>li>a { 94 | display: block; 95 | width: 100%; 96 | color: rgb(30, 30, 30); 97 | text-decoration: none; 98 | } 99 | 100 | .event-list>li>.social>ul>li { 101 | padding: 0px; 102 | } 103 | 104 | .event-list>li>.social>ul>li>a { 105 | padding: 3px 0px; 106 | } 107 | 108 | .event-list>li>.info>ul>li:hover, 109 | .event-list>li>.social>ul>li:hover { 110 | color: rgb(30, 30, 30); 111 | background-color: rgb(200, 200, 200); 112 | } 113 | 114 | .facebook a, 115 | .twitter a, 116 | .google-plus a { 117 | display: block; 118 | width: 100%; 119 | color: rgb(75, 110, 168) !important; 120 | } 121 | 122 | .twitter a { 123 | color: rgb(79, 213, 248) !important; 124 | } 125 | 126 | .google-plus a { 127 | color: rgb(221, 75, 57) !important; 128 | } 129 | 130 | .facebook:hover a { 131 | color: rgb(255, 255, 255) !important; 132 | background-color: rgb(75, 110, 168) !important; 133 | } 134 | 135 | .twitter:hover a { 136 | color: rgb(255, 255, 255) !important; 137 | background-color: rgb(79, 213, 248) !important; 138 | } 139 | 140 | .google-plus:hover a { 141 | color: rgb(255, 255, 255) !important; 142 | background-color: rgb(221, 75, 57) !important; 143 | } 144 | 145 | @media (min-width: 768px) { 146 | .event-list>li { 147 | position: relative; 148 | display: block; 149 | width: 100%; 150 | height: 120px; 151 | padding: 0px; 152 | } 153 | .event-list>li>time, 154 | .event-list>li>img { 155 | display: inline-block; 156 | } 157 | .event-list>li>time, 158 | .event-list>li>img { 159 | width: 120px; 160 | float: left; 161 | } 162 | .event-list>li>.info { 163 | background-color: rgb(245, 245, 245); 164 | overflow: hidden; 165 | } 166 | .event-list>li>time, 167 | .event-list>li>img { 168 | width: 120px; 169 | height: 120px; 170 | padding: 0px; 171 | margin: 0px; 172 | } 173 | .event-list>li>.info { 174 | position: relative; 175 | height: 120px; 176 | text-align: left; 177 | padding-right: 40px; 178 | } 179 | .event-list>li>.info>.title, 180 | .event-list>li>.info>.desc { 181 | padding: 0px 10px; 182 | } 183 | .event-list>li>.info>ul { 184 | position: absolute; 185 | left: 0px; 186 | bottom: 0px; 187 | } 188 | .event-list>li>.social { 189 | position: absolute; 190 | top: 0px; 191 | right: 0px; 192 | display: block; 193 | width: 40px; 194 | } 195 | .event-list>li>.social>ul { 196 | border-left: 1px solid rgb(230, 230, 230); 197 | } 198 | .event-list>li>.social>ul>li { 199 | display: block; 200 | padding: 0px; 201 | } 202 | .event-list>li>.social>ul>li>a { 203 | display: block; 204 | width: 40px; 205 | padding: 10px 0px 9px; 206 | } 207 | } 208 | 209 | .container .container-recents { 210 | padding: 100px; 211 | } -------------------------------------------------------------------------------- /client/src/app/home/home/home.component.html: -------------------------------------------------------------------------------- 1 | 2 |
3 |
4 |
5 |

Your meal for today

6 | 10 |
11 |

12 | 19 |

20 |
21 |
22 |
23 | -------------------------------------------------------------------------------- /client/src/app/home/home/home.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { async, ComponentFixture, TestBed } from '@angular/core/testing'; 2 | import { By } from '@angular/platform-browser'; 3 | import { RouterTestingModule } from '@angular/router/testing'; 4 | import { combineReducers, Store, StoreModule } from '@ngrx/store'; 5 | import { AbstractCameraServiceStub } from '../../../testing/abstractCameraServiceMock'; 6 | import { AbstractNotificationServiceStub } from '../../../testing/abstractNotificationServiceMock'; 7 | import { CpuValueServiceMock } from '../../../testing/CpuValueServiceMock'; 8 | import { FoodServiceMock } from '../../../testing/foodServiceMock'; 9 | import { FoodDataService } from '../../core/data-services/food-data.service'; 10 | import { AbstractCameraService } from '../../core/services/abstract-camera.service'; 11 | import { AbstractNotificationService } from '../../core/services/abstract-notification.service'; 12 | import { CpuValueService } from '../../core/services/desktop-cpuValue.service'; 13 | import { PlatformInformationProvider } from '../../core/services/platform-information.provider'; 14 | import { FoodItem } from '../../shared/models/foodItem.model'; 15 | import * as fromRootStore from '../../store'; 16 | import { EMealFooterComponent } from '../footer/eMeal-footer.component'; 17 | import { RandomMealComponent } from '../randomMeal/randomMeal.component'; 18 | import { SingleMealComponent } from '../single-meal/single-meal.component'; 19 | import * as fromHomeActions from '../store/actions'; 20 | import { HomeStoreFacade } from '../store/home-store.facade'; 21 | import * as fromHomeStore from '../store/reducers'; 22 | import { HomeComponent } from './home.component'; 23 | 24 | describe('HomeComponent', () => { 25 | let fixture: ComponentFixture; 26 | let comp: HomeComponent; 27 | 28 | // async beforeEachs 29 | beforeEach(async(() => { 30 | TestBed.configureTestingModule({ 31 | imports: [ 32 | RouterTestingModule, 33 | StoreModule.forRoot({ 34 | ...fromRootStore.reducers, 35 | home: combineReducers(fromHomeStore.reducers), 36 | }), 37 | ], 38 | declarations: [ 39 | HomeComponent, 40 | RandomMealComponent, 41 | SingleMealComponent, 42 | EMealFooterComponent, 43 | ], 44 | providers: [ 45 | { provide: HomeStoreFacade, useClass: HomeStoreFacade }, 46 | { provide: FoodDataService, useClass: FoodServiceMock }, 47 | { 48 | provide: AbstractNotificationService, 49 | useClass: AbstractNotificationServiceStub, 50 | }, 51 | { provide: CpuValueService, useClass: CpuValueServiceMock }, 52 | { 53 | provide: AbstractCameraService, 54 | useClass: AbstractCameraServiceStub, 55 | }, 56 | PlatformInformationProvider, 57 | ], 58 | }).compileComponents(); // compile template and css 59 | })); 60 | 61 | // synchronous beforeEach 62 | beforeEach(() => { 63 | fixture = TestBed.createComponent(HomeComponent); 64 | comp = fixture.componentInstance; 65 | }); 66 | 67 | afterEach(() => { 68 | fixture.destroy(); 69 | }); 70 | 71 | it('component should be instanciated', () => { 72 | expect(comp).toBeDefined(); 73 | }); 74 | 75 | it('updatefood should be defined', () => { 76 | expect(comp.updateFood).toBeDefined(); 77 | }); 78 | 79 | it('updatefood should dispatch the correct action', () => { 80 | const store = TestBed.get(Store); 81 | const action = new fromHomeActions.LoadRandomMealAction(); 82 | spyOn(store, 'dispatch').and.callThrough(); 83 | 84 | comp.updateFood(); 85 | 86 | expect(store.dispatch).toHaveBeenCalledWith(action); 87 | }); 88 | 89 | it('after init was called `loadRandomMeal` was called one times', () => { 90 | const facade = TestBed.get(HomeStoreFacade); 91 | spyOn(facade, 'loadRandomMeal'); 92 | fixture.detectChanges(); 93 | 94 | expect(facade.loadRandomMeal).toHaveBeenCalledTimes(1); 95 | }); 96 | 97 | it('after init was called "randomMeal$" is set', () => { 98 | fixture.detectChanges(); // call init here 99 | 100 | const foodItem1 = new FoodItem(); 101 | foodItem1.id = 'foodItem1'; 102 | 103 | const foodItem2 = new FoodItem(); 104 | foodItem2.id = 'foodItem2'; 105 | 106 | const items = [foodItem1, foodItem2]; 107 | 108 | const action = new fromHomeActions.LoadRandomMealSuccessAction(items); 109 | const store = TestBed.get(Store); 110 | 111 | store.dispatch(action); 112 | 113 | comp.randomMeal$.subscribe(data => { 114 | expect(data.length).toBe(items.length); 115 | }); 116 | }); 117 | 118 | it('h2 should give correct headline', () => { 119 | const de = fixture.debugElement.query(By.css('h2')); 120 | const el = de.nativeElement; 121 | expect(el.textContent).toEqual('Your meal for today'); 122 | }); 123 | }); 124 | -------------------------------------------------------------------------------- /client/src/app/home/home/home.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { Observable } from 'rxjs'; 3 | import { FoodItem } from '../../shared/models/foodItem.model'; 4 | import { HomeStoreFacade } from '../store/home-store.facade'; 5 | 6 | @Component({ 7 | selector: 'app-home-component', 8 | templateUrl: './home.component.html', 9 | styleUrls: ['./home.component.css'] 10 | }) 11 | export class HomeComponent implements OnInit { 12 | randomMeal$: Observable; 13 | loading$: Observable; 14 | 15 | constructor(private facade: HomeStoreFacade) {} 16 | 17 | ngOnInit() { 18 | this.randomMeal$ = this.facade.randomMeal$; 19 | this.loading$ = this.facade.loading$; 20 | 21 | this.facade.loadRandomMeal(); 22 | } 23 | 24 | updateFood() { 25 | this.facade.loadRandomMeal(); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /client/src/app/home/randomMeal/randomMeal.component.html: -------------------------------------------------------------------------------- 1 |
2 |
3 | 4 |
5 |
6 | 7 | 8 |

Loading...

9 |
-------------------------------------------------------------------------------- /client/src/app/home/randomMeal/randomMeal.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { async, ComponentFixture, TestBed } from '@angular/core/testing'; 2 | import { By } from '@angular/platform-browser'; 3 | import { RouterTestingModule } from '@angular/router/testing'; 4 | import { AbstractCameraServiceStub } from '../../../testing/abstractCameraServiceMock'; 5 | import { AbstractNotificationServiceStub } from '../../../testing/abstractNotificationServiceMock'; 6 | import { CpuValueServiceMock } from '../../../testing/CpuValueServiceMock'; 7 | import { FoodServiceMock } from '../../../testing/foodServiceMock'; 8 | import { FoodDataService } from '../../core/data-services/food-data.service'; 9 | import { AbstractCameraService } from '../../core/services/abstract-camera.service'; 10 | import { AbstractNotificationService } from '../../core/services/abstract-notification.service'; 11 | import { CpuValueService } from '../../core/services/desktop-cpuValue.service'; 12 | import { PlatformInformationProvider } from '../../core/services/platform-information.provider'; 13 | import { FoodItem } from '../../shared/models/foodItem.model'; 14 | import { EMealFooterComponent } from '../footer/eMeal-footer.component'; 15 | import { HomeComponent } from '../home/home.component'; 16 | import { SingleMealComponent } from '../single-meal/single-meal.component'; 17 | import { RandomMealComponent } from './randomMeal.component'; 18 | 19 | describe('RandomMeal Component', () => { 20 | let fixture: ComponentFixture; 21 | let comp: RandomMealComponent; 22 | 23 | class FoodItemFactory { 24 | static getFoodItem() { 25 | const fooditem = new FoodItem(); 26 | fooditem.id = '1'; 27 | fooditem.created = new Date(); 28 | fooditem.calories = 999; 29 | fooditem.type = 'starter'; 30 | fooditem.name = 'FoodItem1'; 31 | 32 | return fooditem; 33 | } 34 | } 35 | 36 | // async beforeEachs 37 | beforeEach(async(() => { 38 | TestBed.configureTestingModule({ 39 | imports: [RouterTestingModule], 40 | declarations: [ 41 | HomeComponent, 42 | RandomMealComponent, 43 | SingleMealComponent, 44 | EMealFooterComponent, 45 | ], 46 | providers: [ 47 | { provide: FoodDataService, useClass: FoodServiceMock }, 48 | { 49 | provide: AbstractNotificationService, 50 | useClass: AbstractNotificationServiceStub, 51 | }, 52 | { provide: CpuValueService, useClass: CpuValueServiceMock }, 53 | { 54 | provide: AbstractCameraService, 55 | useClass: AbstractCameraServiceStub, 56 | }, 57 | PlatformInformationProvider, 58 | ], 59 | }).compileComponents(); // compile template and css 60 | })); 61 | 62 | // synchronous beforeEach 63 | beforeEach(() => { 64 | fixture = TestBed.createComponent(RandomMealComponent); 65 | comp = fixture.componentInstance; 66 | }); 67 | 68 | afterEach(() => { 69 | fixture.destroy(); 70 | }); 71 | 72 | it('component should be instanciated', () => { 73 | expect(comp).toBeDefined(); 74 | }); 75 | 76 | it('if loading is true we hide the app-single-meal-component', () => { 77 | comp.loading = true; 78 | fixture.detectChanges(); 79 | const de = fixture.debugElement.query(By.css('h4')); 80 | expect(de.nativeElement.innerHTML).toBe('Loading...'); 81 | }); 82 | }); 83 | -------------------------------------------------------------------------------- /client/src/app/home/randomMeal/randomMeal.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, Input } from '@angular/core'; 2 | import { FoodItem } from '../../shared/models/foodItem.model'; 3 | 4 | @Component({ 5 | selector: 'app-random-meal', 6 | templateUrl: 'randomMeal.component.html', 7 | }) 8 | export class RandomMealComponent { 9 | @Input() 10 | foodItems: FoodItem[]; 11 | @Input() 12 | loading: boolean; 13 | } 14 | -------------------------------------------------------------------------------- /client/src/app/home/single-meal/single-meal.component.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FabianGosebrink/ASPNETCore-Angular-Ngrx/8c697557c83d8375a1ea06ab5fdfd19348e29204/client/src/app/home/single-meal/single-meal.component.css -------------------------------------------------------------------------------- /client/src/app/home/single-meal/single-meal.component.html: -------------------------------------------------------------------------------- 1 |

{{fooditem?.type}}

2 |

3 | {{fooditem?.name}} 4 |

5 |
{{fooditem?.calories}}
-------------------------------------------------------------------------------- /client/src/app/home/single-meal/single-meal.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { async, ComponentFixture, TestBed } from '@angular/core/testing'; 2 | 3 | import { SingleMealComponent } from './single-meal.component'; 4 | 5 | describe('SingleMealComponent', () => { 6 | let component: SingleMealComponent; 7 | let fixture: ComponentFixture; 8 | 9 | beforeEach( 10 | async(() => { 11 | TestBed.configureTestingModule({ 12 | declarations: [SingleMealComponent] 13 | }).compileComponents(); 14 | }) 15 | ); 16 | 17 | beforeEach(() => { 18 | fixture = TestBed.createComponent(SingleMealComponent); 19 | component = fixture.componentInstance; 20 | fixture.detectChanges(); 21 | }); 22 | 23 | it('should create', () => { 24 | expect(component).toBeTruthy(); 25 | }); 26 | }); 27 | -------------------------------------------------------------------------------- /client/src/app/home/single-meal/single-meal.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, Input, OnInit } from '@angular/core'; 2 | import { FoodItem } from '../../shared/models/foodItem.model'; 3 | 4 | @Component({ 5 | selector: 'app-single-meal', 6 | templateUrl: './single-meal.component.html', 7 | styleUrls: ['./single-meal.component.css'], 8 | }) 9 | export class SingleMealComponent implements OnInit { 10 | @Input() 11 | fooditem: FoodItem; 12 | constructor() {} 13 | 14 | ngOnInit() {} 15 | } 16 | -------------------------------------------------------------------------------- /client/src/app/home/store/actions/home.actions.ts: -------------------------------------------------------------------------------- 1 | import { createAction, props } from '@ngrx/store'; 2 | import { ModelDescriptor } from '@app/shared/models/model.descriptor'; 3 | import { FoodItem } from '@app/shared/models/foodItem.model'; 4 | 5 | export const loadRandomMeal = createAction('[Home] LOAD_RANDOM_MEAL'); 6 | 7 | export const loadRandomMealSuccess = createAction( 8 | '[Home] LOAD_RANDOM_MEAL_SUCCESS', 9 | props<{ payload: ModelDescriptor }>() 10 | ); 11 | 12 | export const loadRandomMealError = createAction( 13 | '[Home] LOAD_RANDOM_MEAL_SUCCESS_ERROR', 14 | props<{ payload: any }>() 15 | ); 16 | -------------------------------------------------------------------------------- /client/src/app/home/store/actions/index.ts: -------------------------------------------------------------------------------- 1 | export * from './home.actions'; 2 | -------------------------------------------------------------------------------- /client/src/app/home/store/effects/home.effects.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { FoodDataService } from '@app/core/data-services/food-data.service'; 3 | import { AbstractNotificationService } from '@app/core/services/abstract-notification.service'; 4 | import { Actions, Effect, ofType, createEffect } from '@ngrx/effects'; 5 | import { of } from 'rxjs'; 6 | import { catchError, map, switchMap, tap } from 'rxjs/operators'; 7 | import * as homeActions from '../actions/home.actions'; 8 | 9 | @Injectable() 10 | export class HomeEffects { 11 | loadRandomMeal$ = createEffect(() => 12 | this.actions$.pipe( 13 | ofType(homeActions.loadRandomMeal), 14 | switchMap(() => 15 | this.foodDataService.getRandomMeal().pipe( 16 | map(data => homeActions.loadRandomMealSuccess({ payload: data })), 17 | catchError(error => 18 | of(homeActions.loadRandomMealError({ payload: error })) 19 | ) 20 | ) 21 | ) 22 | ) 23 | ); 24 | 25 | homeError$ = createEffect( 26 | () => 27 | this.actions$.pipe( 28 | ofType(homeActions.loadRandomMealError), 29 | tap(({ payload }) => 30 | this.notificationService.showError('Home', payload.error.statusText) 31 | ) 32 | ), 33 | { dispatch: false } 34 | ); 35 | 36 | constructor( 37 | private foodDataService: FoodDataService, 38 | private notificationService: AbstractNotificationService, 39 | private actions$: Actions 40 | ) {} 41 | } 42 | -------------------------------------------------------------------------------- /client/src/app/home/store/effects/index.ts: -------------------------------------------------------------------------------- 1 | import { HomeEffects } from './home.effects'; 2 | 3 | export const effects: any[] = [HomeEffects]; 4 | 5 | export * from './home.effects'; 6 | -------------------------------------------------------------------------------- /client/src/app/home/store/home-store.facade.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { select, Store } from '@ngrx/store'; 3 | import * as fromActions from './actions'; 4 | import * as fromReducers from './reducers'; 5 | import * as fromSelectors from './selectors'; 6 | 7 | @Injectable({ providedIn: 'root' }) 8 | export class HomeStoreFacade { 9 | loading$ = this.store.pipe(select(fromSelectors.getLoading)); 10 | randomMeal$ = this.store.pipe(select(fromSelectors.getRandomMeal)); 11 | 12 | constructor(private store: Store) {} 13 | 14 | loadRandomMeal() { 15 | this.store.dispatch(fromActions.loadRandomMeal()); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /client/src/app/home/store/reducers/home.reducer.ts: -------------------------------------------------------------------------------- 1 | import * as homeActions from '../actions/home.actions'; 2 | import { on, createReducer, Action } from '@ngrx/store'; 3 | import { FoodItem } from '@app/shared/models/foodItem.model'; 4 | 5 | export interface HomeReduerState { 6 | randomMeal: { [id: string]: FoodItem }; 7 | loading: boolean; 8 | loaded: boolean; 9 | } 10 | 11 | export const initialState: HomeReduerState = { 12 | randomMeal: {}, 13 | loading: false, 14 | loaded: false 15 | }; 16 | 17 | const homeReducerInternal = createReducer( 18 | initialState, 19 | on(homeActions.loadRandomMeal, (state, {}) => { 20 | return { 21 | ...state, 22 | loading: true 23 | }; 24 | }), 25 | 26 | on(homeActions.loadRandomMealSuccess, (state, { payload }) => { 27 | const values = payload.value; 28 | const randomMeal: { [id: string]: FoodItem } = {}; 29 | values.forEach((item: FoodItem) => { 30 | if (item) { 31 | randomMeal[item.id] = item; 32 | } else { 33 | randomMeal[''] = null; 34 | } 35 | }); 36 | 37 | return { 38 | ...state, 39 | randomMeal, 40 | loaded: true, 41 | loading: false 42 | }; 43 | }) 44 | ); 45 | 46 | export function homeReducer( 47 | state: HomeReduerState | undefined, 48 | action: Action 49 | ) { 50 | return homeReducerInternal(state, action); 51 | } 52 | 53 | export const getRandomMeal = (state: HomeReduerState) => state.randomMeal; 54 | export const getRandomMealLoaded = (state: HomeReduerState) => state.loaded; 55 | export const getRandomMealLoading = (state: HomeReduerState) => state.loading; 56 | -------------------------------------------------------------------------------- /client/src/app/home/store/reducers/index.ts: -------------------------------------------------------------------------------- 1 | import * as fromHome from './home.reducer'; 2 | import { ActionReducerMap, createFeatureSelector } from '@ngrx/store'; 3 | 4 | export interface HomeState { 5 | home: fromHome.HomeReduerState; 6 | } 7 | 8 | export const reducers: ActionReducerMap = { 9 | home: fromHome.homeReducer 10 | }; 11 | 12 | export const getHomeState = createFeatureSelector('home'); 13 | -------------------------------------------------------------------------------- /client/src/app/home/store/selectors/home.selectors.ts: -------------------------------------------------------------------------------- 1 | import { createSelector } from '@ngrx/store'; 2 | import * as fromFeature from '../reducers'; 3 | import * as fromHome from '../reducers/home.reducer'; 4 | 5 | export const getCompleteHomeState = createSelector( 6 | fromFeature.getHomeState, 7 | (state: fromFeature.HomeState) => state.home 8 | ); 9 | 10 | const getRandomMealState = createSelector( 11 | getCompleteHomeState, 12 | fromHome.getRandomMeal 13 | ); 14 | 15 | export const getRandomMeal = createSelector(getRandomMealState, entities => { 16 | return Object.keys(entities).map(id => entities[id]); 17 | }); 18 | 19 | export const getLoading = createSelector( 20 | getCompleteHomeState, 21 | fromHome.getRandomMealLoading 22 | ); 23 | 24 | export const getLoaded = createSelector( 25 | getCompleteHomeState, 26 | fromHome.getRandomMealLoaded 27 | ); 28 | -------------------------------------------------------------------------------- /client/src/app/home/store/selectors/index.ts: -------------------------------------------------------------------------------- 1 | export * from './home.selectors'; 2 | -------------------------------------------------------------------------------- /client/src/app/shared/components/footer/eMeail-footer.component.spec.ts: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FabianGosebrink/ASPNETCore-Angular-Ngrx/8c697557c83d8375a1ea06ab5fdfd19348e29204/client/src/app/shared/components/footer/eMeail-footer.component.spec.ts -------------------------------------------------------------------------------- /client/src/app/shared/components/footer/eMeal-footer.component.html: -------------------------------------------------------------------------------- 1 |
2 |

3 | 2019 Offering Solutions 4 | 5 | - running on desktop CPU (%): {{ percentage }} 7 | 8 | - running on mobile: {{ platformName }} 10 | 11 | - running on web {{ userAgent }} 13 |

14 |
15 | -------------------------------------------------------------------------------- /client/src/app/shared/components/footer/eMeal-footer.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, NgZone } from '@angular/core'; 2 | import { CpuValueService } from '@app/core/services/desktop-cpuValue.service'; 3 | import { PlatformInformationProvider } from '@app/core/services/platform-information.provider'; 4 | import { environment } from '@environments/environment'; 5 | 6 | @Component({ 7 | selector: 'app-emeal-footer', 8 | templateUrl: 'eMeal-footer.component.html', 9 | }) 10 | export class EMealFooterComponent { 11 | percentage: string; 12 | 13 | get currentEnvironment() { 14 | return environment; 15 | } 16 | 17 | get platformName() { 18 | return this.platformInformationProvider.platformName; 19 | } 20 | 21 | get userAgent() { 22 | return this.platformInformationProvider.userAgent; 23 | } 24 | 25 | constructor( 26 | private platformInformationProvider: PlatformInformationProvider, 27 | private cpuValueService: CpuValueService, 28 | private ngZone: NgZone 29 | ) { 30 | this.cpuValueService.onNewCpuValue.subscribe((cpuValue: string) => { 31 | this.ngZone.run(() => { 32 | this.percentage = cpuValue; 33 | }); 34 | }); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /client/src/app/shared/components/navigation/navigation.component.html: -------------------------------------------------------------------------------- 1 | 30 | -------------------------------------------------------------------------------- /client/src/app/shared/components/navigation/navigation.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { DebugElement } from '@angular/core'; 2 | import { 3 | async, 4 | ComponentFixture, 5 | inject, 6 | TestBed, 7 | } from '@angular/core/testing'; 8 | import { By } from '@angular/platform-browser'; 9 | import { combineReducers, StoreModule } from '@ngrx/store'; 10 | import { AuthenticationServiceStub } from '../../../../testing/authenticationserviceMock'; 11 | import { AuthenticationService } from '../../../core/services/authentication.service'; 12 | import { CurrentUserService } from '../../../core/services/currentUser.service'; 13 | import { StorageService } from '../../../core/services/storage.service'; 14 | import * as fromCoreStoreReducers from '../../../core/store/reducers'; 15 | import * as fromRootStore from '../../../store'; 16 | import { Configuration } from '../../configuration/app.configuration'; 17 | import { NavigationComponent } from './navigation.component'; 18 | 19 | describe('NavigationComponent', () => { 20 | let fixture: ComponentFixture; 21 | let comp: NavigationComponent; 22 | 23 | // async beforeEach 24 | beforeEach(async(() => { 25 | TestBed.configureTestingModule({ 26 | imports: [ 27 | StoreModule.forRoot({ 28 | ...fromRootStore.reducers, 29 | core: combineReducers(fromCoreStoreReducers.reducers), 30 | }), 31 | ], 32 | declarations: [NavigationComponent], 33 | providers: [ 34 | Configuration, 35 | CurrentUserService, 36 | { 37 | provide: AuthenticationService, 38 | useClass: AuthenticationServiceStub, 39 | }, 40 | StorageService, 41 | ], 42 | }).compileComponents(); // compile template and css 43 | })); 44 | 45 | // synchronous beforeEach 46 | beforeEach(() => { 47 | fixture = TestBed.createComponent(NavigationComponent); 48 | comp = fixture.componentInstance; 49 | fixture.detectChanges(); // trigger initial data binding 50 | }); 51 | 52 | afterEach(() => { 53 | fixture.destroy(); 54 | }); 55 | 56 | it('component should be instanciated', () => { 57 | expect(comp).toBeDefined(); 58 | }); 59 | 60 | it('configuration should be defined', inject( 61 | [Configuration], 62 | (service: Configuration) => { 63 | expect(comp.configuration).toBeDefined(); 64 | } 65 | )); 66 | 67 | it('Title is displayed correctly', inject( 68 | [Configuration], 69 | (service: Configuration) => { 70 | let de: DebugElement; 71 | let el: HTMLElement; 72 | de = fixture.debugElement.query(By.css('.navbar-brand')); 73 | el = de.nativeElement; 74 | expect(el.innerText).toContain(service.title); 75 | } 76 | )); 77 | }); 78 | -------------------------------------------------------------------------------- /client/src/app/shared/components/navigation/navigation.component.ts: -------------------------------------------------------------------------------- 1 | import { Component } from '@angular/core'; 2 | import { CurrentUserService } from '@app/core/services/currentUser.service'; 3 | import { Configuration } from '@app/shared/configuration/app.configuration'; 4 | import { Observable } from 'rxjs'; 5 | 6 | @Component({ 7 | selector: 'app-navigation', 8 | templateUrl: 'navigation.component.html', 9 | }) 10 | export class NavigationComponent { 11 | isAuthenticated$: Observable; 12 | 13 | constructor( 14 | public configuration: Configuration, 15 | public currentUserService: CurrentUserService 16 | ) {} 17 | 18 | doNothing($event: Event) { 19 | $event.preventDefault(); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /client/src/app/shared/configuration/app.configuration.spec.ts: -------------------------------------------------------------------------------- 1 | import { ToasterConfig } from 'angular2-toaster'; 2 | import { environment } from '../../../environments/environment'; 3 | import { Configuration } from './app.configuration'; 4 | 5 | describe('Configuration', () => { 6 | let service: Configuration; 7 | beforeEach(() => { 8 | service = new Configuration(); 9 | }); 10 | 11 | it('Returns the correct title', () => { 12 | expect(service.title).toBe('eMeal'); 13 | }); 14 | 15 | it('BaseUrl should be azure or localhost', () => { 16 | const possibleUrls = [ 17 | 'http://foodapi4demo.azurewebsites.net/api/', 18 | 'http://localhost:51777/api/' 19 | ]; 20 | 21 | console.log(environment); 22 | expect( 23 | possibleUrls.indexOf(environment.server + environment.apiUrl) 24 | ).toBeGreaterThanOrEqual(0); 25 | }); 26 | 27 | it('BaseUrl ends with a slash', () => { 28 | const lastChar = environment.apiUrl.slice(-1); 29 | expect(lastChar).toBe('/'); 30 | }); 31 | 32 | it('ToasterConfig is of Type "Toasterconfig"', () => { 33 | expect(service.toasterConfig).toEqual(jasmine.any(ToasterConfig)); 34 | }); 35 | 36 | it('ToasterConfig places toasts on the bottom right corner', () => { 37 | expect(service.toasterConfig.positionClass).toEqual('toast-bottom-right'); 38 | }); 39 | }); 40 | -------------------------------------------------------------------------------- /client/src/app/shared/configuration/app.configuration.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | 3 | @Injectable() 4 | export class Configuration { 5 | title = 'eMeal'; 6 | } 7 | -------------------------------------------------------------------------------- /client/src/app/shared/models/foodItem.model.ts: -------------------------------------------------------------------------------- 1 | export class FoodItem { 2 | public id: string; // GUID 3 | public calories: number; 4 | public name: string; 5 | public type: string; 6 | public created: Date; 7 | public imageString: string; 8 | } 9 | -------------------------------------------------------------------------------- /client/src/app/shared/models/ingredient.model.ts: -------------------------------------------------------------------------------- 1 | export class Ingredient { 2 | public id: string; 3 | public quantity: number; 4 | public weight: number; 5 | public description: string; 6 | } 7 | -------------------------------------------------------------------------------- /client/src/app/shared/models/model.descriptor.ts: -------------------------------------------------------------------------------- 1 | export class ModelDescriptor { 2 | links: Links[]; 3 | value: T; 4 | } 5 | 6 | export class Links { 7 | href: string; 8 | method: string; 9 | rel: string; 10 | } 11 | -------------------------------------------------------------------------------- /client/src/app/shared/shared.module.ts: -------------------------------------------------------------------------------- 1 | import { CommonModule } from '@angular/common'; 2 | import { NgModule } from '@angular/core'; 3 | import { RouterModule } from '@angular/router'; 4 | import { EMealFooterComponent } from './components/footer/eMeal-footer.component'; 5 | import { NavigationComponent } from './components/navigation/navigation.component'; 6 | import { Configuration } from './configuration/app.configuration'; 7 | 8 | @NgModule({ 9 | imports: [ 10 | // Modules 11 | CommonModule, 12 | RouterModule, 13 | ], 14 | 15 | declarations: [ 16 | // Components & directives 17 | NavigationComponent, 18 | EMealFooterComponent, 19 | ], 20 | 21 | providers: [ 22 | // Services 23 | Configuration, 24 | ], 25 | 26 | exports: [NavigationComponent, EMealFooterComponent], 27 | }) 28 | export class SharedModule {} 29 | -------------------------------------------------------------------------------- /client/src/app/store/index.ts: -------------------------------------------------------------------------------- 1 | export * from './reducers'; 2 | -------------------------------------------------------------------------------- /client/src/app/store/reducers/index.ts: -------------------------------------------------------------------------------- 1 | export * from './router.reducer'; 2 | -------------------------------------------------------------------------------- /client/src/app/store/reducers/router.reducer.ts: -------------------------------------------------------------------------------- 1 | import { 2 | ActivatedRouteSnapshot, 3 | Params, 4 | RouterStateSnapshot, 5 | } from '@angular/router'; 6 | import * as fromRouter from '@ngrx/router-store'; 7 | import { ActionReducerMap, createFeatureSelector } from '@ngrx/store'; 8 | 9 | export interface RouterStateUrl { 10 | url: string; 11 | queryParams: Params; 12 | params: Params; 13 | } 14 | 15 | export interface State { 16 | routerReducer: fromRouter.RouterReducerState; 17 | } 18 | 19 | export const reducers: ActionReducerMap = { 20 | routerReducer: fromRouter.routerReducer, 21 | }; 22 | 23 | export const getRouterState = createFeatureSelector< 24 | fromRouter.RouterReducerState 25 | >('routerReducer'); 26 | 27 | export class CustomSerializer 28 | implements fromRouter.RouterStateSerializer { 29 | serialize(routerState: RouterStateSnapshot): RouterStateUrl { 30 | const { url } = routerState; 31 | const { queryParams } = routerState.root; 32 | let state: ActivatedRouteSnapshot = routerState.root; 33 | 34 | while (state.firstChild) { 35 | state = state.firstChild; 36 | } 37 | 38 | const { params } = state; 39 | 40 | return { url, queryParams, params }; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /client/src/assets/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FabianGosebrink/ASPNETCore-Angular-Ngrx/8c697557c83d8375a1ea06ab5fdfd19348e29204/client/src/assets/.gitkeep -------------------------------------------------------------------------------- /client/src/cordova.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FabianGosebrink/ASPNETCore-Angular-Ngrx/8c697557c83d8375a1ea06ab5fdfd19348e29204/client/src/cordova.js -------------------------------------------------------------------------------- /client/src/environments/environment.desktop.ts: -------------------------------------------------------------------------------- 1 | export const environment = { 2 | production: true, 3 | mobile: false, 4 | desktop: true, 5 | server: 'https://conference-xplatform-server.azurewebsites.net/', 6 | apiUrl: 'api/', 7 | }; 8 | -------------------------------------------------------------------------------- /client/src/environments/environment.mobile.ts: -------------------------------------------------------------------------------- 1 | export const environment = { 2 | production: true, 3 | mobile: true, 4 | desktop: false, 5 | server: 'https://conference-xplatform-server.azurewebsites.net/', 6 | apiUrl: 'api/', 7 | }; 8 | -------------------------------------------------------------------------------- /client/src/environments/environment.prod.ts: -------------------------------------------------------------------------------- 1 | export const environment = { 2 | production: true, 3 | mobile: false, 4 | desktop: false, 5 | server: 'https://conference-xplatform-server.azurewebsites.net/', 6 | apiUrl: 'api/', 7 | }; 8 | -------------------------------------------------------------------------------- /client/src/environments/environment.ts: -------------------------------------------------------------------------------- 1 | // The file contents for the current environment will overwrite these during build. 2 | // The build system defaults to the dev environment which uses `environment.ts`, but if you do 3 | // `ng build --env=prod` then `environment.prod.ts` will be used instead. 4 | // The list of which env maps to which file can be found in `.angular-cli.json`. 5 | 6 | export const environment = { 7 | production: false, 8 | mobile: false, 9 | desktop: false, 10 | server: 'https://conference-xplatform-server.azurewebsites.net/', 11 | apiUrl: 'api/' 12 | }; 13 | -------------------------------------------------------------------------------- /client/src/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FabianGosebrink/ASPNETCore-Angular-Ngrx/8c697557c83d8375a1ea06ab5fdfd19348e29204/client/src/favicon.ico -------------------------------------------------------------------------------- /client/src/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | eMeal 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | Loading... 16 | 17 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /client/src/main.ts: -------------------------------------------------------------------------------- 1 | import { enableProdMode } from '@angular/core'; 2 | import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; 3 | import { AppModule } from './app/app.module'; 4 | import { environment } from './environments/environment'; 5 | 6 | if (environment.production) { 7 | enableProdMode(); 8 | } 9 | 10 | const bootstrap = () => 11 | platformBrowserDynamic() 12 | .bootstrapModule(AppModule) 13 | .catch(err => console.error(err)); 14 | 15 | if (environment.mobile) { 16 | document.addEventListener('deviceready', bootstrap); 17 | } else { 18 | bootstrap(); 19 | } 20 | -------------------------------------------------------------------------------- /client/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__UNPATCHED_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 | getWindow().$ = getWindow().jQuery = require("jquery"); 61 | 62 | function getWindow(): any { 63 | return window; 64 | } 65 | -------------------------------------------------------------------------------- /client/src/styles.css: -------------------------------------------------------------------------------- 1 | /* You can add global styles to this file, and also import other style files */ 2 | body { 3 | padding-top: 5rem; 4 | padding-bottom: 30px; 5 | } 6 | 7 | .starter-template { 8 | text-align: center; 9 | } 10 | .bd-placeholder-img { 11 | font-size: 1.125rem; 12 | text-anchor: middle; 13 | } 14 | 15 | @media (min-width: 768px) { 16 | .bd-placeholder-img-lg { 17 | font-size: 3.5rem; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /client/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: { 11 | context(path: string, deep?: boolean, filter?: RegExp): { 12 | keys(): string[]; 13 | (id: string): T; 14 | }; 15 | }; 16 | 17 | // First, initialize the Angular testing environment. 18 | getTestBed().initTestEnvironment( 19 | BrowserDynamicTestingModule, 20 | platformBrowserDynamicTesting() 21 | ); 22 | // Then we find all the tests. 23 | const context = require.context('./', true, /\.spec\.ts$/); 24 | // And load the modules. 25 | context.keys().map(context); 26 | -------------------------------------------------------------------------------- /client/src/testing/CpuValueServiceMock.ts: -------------------------------------------------------------------------------- 1 | import { EventEmitter, Injectable } from '@angular/core'; 2 | 3 | @Injectable() 4 | export class CpuValueServiceMock { 5 | onNewCpuValue = new EventEmitter(); 6 | 7 | private registerCpuEvent() { 8 | console.log(); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /client/src/testing/abstractCameraServiceMock.ts: -------------------------------------------------------------------------------- 1 | import { Observable, of } from 'rxjs'; 2 | 3 | export class AbstractCameraServiceStub { 4 | getPhoto(): Observable { 5 | return of(''); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /client/src/testing/abstractNotificationServiceMock.ts: -------------------------------------------------------------------------------- 1 | export class AbstractNotificationServiceStub { 2 | showError(title: string, message: string, icon?: string) {} 3 | 4 | showInfo(title: string, message: string, icon?: string) {} 5 | 6 | showWait(title: string, message: string, icon?: string) {} 7 | 8 | showSuccess(title: string, message: string, icon?: string) {} 9 | 10 | showWarning(title: string, message: string, icon?: string) {} 11 | } 12 | -------------------------------------------------------------------------------- /client/src/testing/foodServiceMock.ts: -------------------------------------------------------------------------------- 1 | import { HttpResponse } from '@angular/common/http'; 2 | import { Injectable } from '@angular/core'; 3 | import { Observable } from 'rxjs'; 4 | import { FoodItem } from '../app/shared/models/foodItem.model'; 5 | 6 | @Injectable() 7 | export class FoodServiceMock { 8 | private internalFoodList: any[] = []; 9 | 10 | constructor() { 11 | const fooditem = new FoodItem(); 12 | fooditem.id = this.getRandomNumber(0, 9999).toString(); 13 | fooditem.created = new Date(); 14 | fooditem.calories = this.getRandomNumber(0, 99999); 15 | fooditem.name = 'FoodItem1'; 16 | this.internalFoodList.push(fooditem); 17 | } 18 | 19 | getAllFood(): Observable { 20 | return Observable.create((observer: any) => { 21 | // Yield a single value and complete 22 | observer.next(this.internalFoodList); 23 | observer.complete(); 24 | }); 25 | } 26 | 27 | getSingleFood(id: number): Observable { 28 | return Observable.create((observer: any) => { 29 | // Yield a single value and complete 30 | observer.next(this.internalFoodList.find(x => x.id === id)); 31 | observer.complete(); 32 | }); 33 | } 34 | 35 | addFood(foodItem: FoodItem): Observable { 36 | return Observable.create((observer: any) => { 37 | // Yield a single value and complete 38 | this.internalFoodList.push(foodItem); 39 | observer.next(foodItem); 40 | observer.complete(); 41 | }); 42 | } 43 | 44 | updateFood(id: string, foodToUpdate: FoodItem): Observable { 45 | return Observable.create((observer: any) => { 46 | // Yield a single value and complete 47 | this.internalFoodList.forEach((item: FoodItem) => { 48 | if (item.id === id) { 49 | item = foodToUpdate; 50 | } 51 | }); 52 | 53 | observer.next(foodToUpdate); 54 | observer.complete(); 55 | }); 56 | } 57 | 58 | deleteFood(id: number): Observable> { 59 | return Observable.create((observer: any) => { 60 | const itemToRemove = this.internalFoodList.find(x => x.id === id); 61 | const indexToRemove = this.internalFoodList.indexOf(itemToRemove); 62 | this.internalFoodList.splice(indexToRemove, 1); 63 | 64 | observer.next( 65 | new HttpResponse({ 66 | status: 204 67 | }) 68 | ); 69 | observer.complete(); 70 | }); 71 | } 72 | 73 | getRandomMeal(): Observable { 74 | return Observable.create((observer: any) => { 75 | observer.next([new FoodItem(), new FoodItem(), new FoodItem()]); 76 | observer.complete(); 77 | }); 78 | } 79 | 80 | private getRandomNumber(min: number, max: number): number { 81 | return Math.floor(Math.random() * max) + min; 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /client/tsconfig.app.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "./out-tsc/app", 5 | "types": [], 6 | }, 7 | "files": [ 8 | "src/main.ts", 9 | "src/polyfills.ts" 10 | ], 11 | "include": [ 12 | "src/**/*.d.ts" 13 | ] 14 | } -------------------------------------------------------------------------------- /client/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compileOnSave": false, 3 | "compilerOptions": { 4 | "baseUrl": "./", 5 | "outDir": "./dist/out-tsc", 6 | "sourceMap": true, 7 | "declaration": false, 8 | "downlevelIteration": true, 9 | "experimentalDecorators": true, 10 | "module": "esnext", 11 | "moduleResolution": "node", 12 | "importHelpers": true, 13 | "target": "es5", 14 | "typeRoots": [ 15 | "node_modules/@types" 16 | ], 17 | "lib": [ 18 | "es2018", 19 | "dom" 20 | ], 21 | "paths": { 22 | "@app/*": [ 23 | "src/app/*" 24 | ], 25 | "@environments/*": [ 26 | "src/environments/*" 27 | ] 28 | } 29 | }, 30 | "angularCompilerOptions": { 31 | "fullTemplateTypeCheck": true, 32 | "strictInjectionParameters": true 33 | } 34 | } -------------------------------------------------------------------------------- /client/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 | "src/test.ts", 12 | "src/polyfills.ts" 13 | ], 14 | "include": [ 15 | "src/**/*.spec.ts", 16 | "src/**/*.d.ts" 17 | ] 18 | } 19 | -------------------------------------------------------------------------------- /client/tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "tslint:recommended", 3 | "rules": { 4 | "array-type": false, 5 | "arrow-parens": false, 6 | "deprecation": { 7 | "severity": "warning" 8 | }, 9 | "component-class-suffix": true, 10 | "contextual-lifecycle": true, 11 | "directive-class-suffix": true, 12 | "directive-selector": [ 13 | true, 14 | "attribute", 15 | "app", 16 | "camelCase" 17 | ], 18 | "component-selector": [ 19 | true, 20 | "element", 21 | "app", 22 | "kebab-case" 23 | ], 24 | "import-blacklist": [ 25 | true, 26 | "rxjs/Rx" 27 | ], 28 | "interface-name": false, 29 | "max-classes-per-file": false, 30 | "max-line-length": [ 31 | true, 32 | 140 33 | ], 34 | "member-access": false, 35 | "member-ordering": [ 36 | true, 37 | { 38 | "order": [ 39 | "static-field", 40 | "instance-field", 41 | "static-method", 42 | "instance-method" 43 | ] 44 | } 45 | ], 46 | "no-consecutive-blank-lines": false, 47 | "no-console": [ 48 | true, 49 | "debug", 50 | "info", 51 | "time", 52 | "timeEnd", 53 | "trace" 54 | ], 55 | "no-empty": false, 56 | "no-inferrable-types": [ 57 | true, 58 | "ignore-params" 59 | ], 60 | "no-non-null-assertion": true, 61 | "no-redundant-jsdoc": true, 62 | "no-switch-case-fall-through": true, 63 | "no-var-requires": false, 64 | "object-literal-key-quotes": [ 65 | true, 66 | "as-needed" 67 | ], 68 | "object-literal-sort-keys": false, 69 | "ordered-imports": false, 70 | "quotemark": [ 71 | true, 72 | "single" 73 | ], 74 | "trailing-comma": false, 75 | "no-conflicting-lifecycle": true, 76 | "no-host-metadata-property": true, 77 | "no-input-rename": true, 78 | "no-inputs-metadata-property": true, 79 | "no-output-native": true, 80 | "no-output-on-prefix": true, 81 | "no-output-rename": true, 82 | "no-outputs-metadata-property": true, 83 | "template-banana-in-box": true, 84 | "template-no-negated-async": true, 85 | "use-lifecycle-interface": true, 86 | "use-pipe-transform-interface": true 87 | }, 88 | "rulesDirectory": [ 89 | "codelyzer" 90 | ] 91 | } -------------------------------------------------------------------------------- /server/ASP.NETCore/FoodAPICore.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 15 4 | VisualStudioVersion = 15.0.26403.3 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{A17F4F44-6C2D-48C1-BA07-4710F3AB47BD}" 7 | EndProject 8 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{05CD7115-E965-48BA-A332-9205C0D21154}" 9 | EndProject 10 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "FoodAPICore", "src\FoodAPICore\FoodAPICore.csproj", "{E3DA9F29-3C55-4781-BF8C-384BF5276A8E}" 11 | EndProject 12 | Global 13 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 14 | Debug|Any CPU = Debug|Any CPU 15 | Release|Any CPU = Release|Any CPU 16 | EndGlobalSection 17 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 18 | {E3DA9F29-3C55-4781-BF8C-384BF5276A8E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 19 | {E3DA9F29-3C55-4781-BF8C-384BF5276A8E}.Debug|Any CPU.Build.0 = Debug|Any CPU 20 | {E3DA9F29-3C55-4781-BF8C-384BF5276A8E}.Release|Any CPU.ActiveCfg = Release|Any CPU 21 | {E3DA9F29-3C55-4781-BF8C-384BF5276A8E}.Release|Any CPU.Build.0 = Release|Any CPU 22 | EndGlobalSection 23 | GlobalSection(SolutionProperties) = preSolution 24 | HideSolutionNode = FALSE 25 | EndGlobalSection 26 | GlobalSection(NestedProjects) = preSolution 27 | {E3DA9F29-3C55-4781-BF8C-384BF5276A8E} = {A17F4F44-6C2D-48C1-BA07-4710F3AB47BD} 28 | EndGlobalSection 29 | EndGlobal 30 | -------------------------------------------------------------------------------- /server/ASP.NETCore/src/FoodAPICore/.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "0.2.0", 3 | "configurations": [ 4 | { 5 | "name": ".NET Core Launch (console)", 6 | "type": "coreclr", 7 | "request": "launch", 8 | "preLaunchTask": "build", 9 | "program": "${workspaceRoot}/bin/Debug/netcoreapp1.1/FoodAPICore.dll", 10 | "args": [], 11 | "cwd": "${workspaceRoot}", 12 | "stopAtEntry": false, 13 | "externalConsole": false 14 | }, 15 | { 16 | "name": ".NET Core Launch (web)", 17 | "type": "coreclr", 18 | "request": "launch", 19 | "preLaunchTask": "build", 20 | "program": "${workspaceRoot}/bin/Debug/netcoreapp1.1/FoodAPICore.dll", 21 | "args": [], 22 | "cwd": "${workspaceRoot}", 23 | "stopAtEntry": false, 24 | "launchBrowser": { 25 | "enabled": true, 26 | "args": "${auto-detect-url}", 27 | "windows": { 28 | "command": "cmd.exe", 29 | "args": "/C start ${auto-detect-url}" 30 | }, 31 | "osx": { 32 | "command": "open" 33 | }, 34 | "linux": { 35 | "command": "xdg-open" 36 | } 37 | }, 38 | "env": { 39 | "ASPNETCORE_ENVIRONMENT": "Development" 40 | }, 41 | "sourceFileMap": { 42 | "/Views": "${workspaceRoot}/Views" 43 | } 44 | }, 45 | { 46 | "name": ".NET Core Attach", 47 | "type": "coreclr", 48 | "request": "attach", 49 | "processId": "${command.pickProcess}" 50 | } 51 | ] 52 | } -------------------------------------------------------------------------------- /server/ASP.NETCore/src/FoodAPICore/Dtos/FoodCreateDto.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | namespace FoodAPICore.Dtos 5 | { 6 | public class FoodCreateDto 7 | { 8 | public string Name { get; set; } 9 | public string Type { get; set; } 10 | public int Calories { get; set; } 11 | public DateTime Created { get; set; } 12 | 13 | public ICollection Ingredients { get; set; } = new List(); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /server/ASP.NETCore/src/FoodAPICore/Dtos/FoodItemDto.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace FoodAPICore.Dtos 4 | { 5 | public class FoodItemDto 6 | { 7 | public Guid Id { get; set; } 8 | public string Name { get; set; } 9 | public int Calories { get; set; } 10 | public string Type { get; set; } 11 | public DateTime Created { get; set; } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /server/ASP.NETCore/src/FoodAPICore/Dtos/FoodUpdateDto.cs: -------------------------------------------------------------------------------- 1 | namespace FoodAPICore.Dtos 2 | { 3 | public class FoodUpdateDto 4 | { 5 | public string Name { get; set; } 6 | public string Type { get; set; } 7 | public int Calories { get; set; } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /server/ASP.NETCore/src/FoodAPICore/Dtos/IngredientDto.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace FoodAPICore.Dtos 4 | { 5 | public class IngredientDto 6 | { 7 | public Guid Id { get; set; } 8 | 9 | public int Quantity { get; set; } 10 | 11 | public int Weight { get; set; } 12 | 13 | public string Description { get; set; } 14 | 15 | public FoodItemDto FoodItem { get; set; } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /server/ASP.NETCore/src/FoodAPICore/Dtos/IngredientUpdateDto.cs: -------------------------------------------------------------------------------- 1 | namespace FoodAPICore.Dtos 2 | { 3 | public class IngredientUpdateDto 4 | { 5 | public int Quantity { get; set; } 6 | 7 | public int Weight { get; set; } 8 | 9 | public string Description { get; set; } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /server/ASP.NETCore/src/FoodAPICore/Dtos/LinkDto.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | 6 | namespace FoodAPICore.Dtos 7 | { 8 | public class LinkDto 9 | { 10 | public string Href { get; set; } 11 | public string Rel { get; set; } 12 | public string Method { get; set; } 13 | 14 | public LinkDto(string href, string rel, string method) 15 | { 16 | Href = href; 17 | Rel = rel; 18 | Method = method; 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /server/ASP.NETCore/src/FoodAPICore/Entities/FoodDbContext.cs: -------------------------------------------------------------------------------- 1 | using FoodAPICore.Models; 2 | using Microsoft.EntityFrameworkCore; 3 | 4 | namespace FoodAPICore.Entities 5 | { 6 | public class FoodDbContext : DbContext 7 | { 8 | public FoodDbContext(DbContextOptions options) 9 | : base(options) 10 | { 11 | 12 | } 13 | 14 | public DbSet FoodItems { get; set; } 15 | public DbSet Ingredients { get; set; } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /server/ASP.NETCore/src/FoodAPICore/Entities/FoodItem.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.ComponentModel.DataAnnotations; 4 | 5 | namespace FoodAPICore.Models 6 | { 7 | public class FoodItem 8 | { 9 | [Key] 10 | public Guid Id { get; set; } 11 | public string Name { get; set; } 12 | public string Type { get; set; } 13 | public int Calories { get; set; } 14 | public DateTime Created { get; set; } 15 | 16 | public List Ingredients { get; set; } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /server/ASP.NETCore/src/FoodAPICore/Entities/Ingredient.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.ComponentModel.DataAnnotations; 3 | 4 | namespace FoodAPICore.Models 5 | { 6 | public class Ingredient 7 | { 8 | [Key] 9 | public Guid Id { get; set; } 10 | 11 | public int Quantity { get; set; } 12 | 13 | public int Weight { get; set; } 14 | 15 | public string Description { get; set; } 16 | 17 | public FoodItem FoodItem { get; set; } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /server/ASP.NETCore/src/FoodAPICore/FoodAPICore.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | netcoreapp3.0 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | all 17 | runtime; build; native; contentfiles; analyzers; buildtransitive 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /server/ASP.NETCore/src/FoodAPICore/FoodAPICore.csproj.user: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | ProjectDebugger 5 | 6 | 7 | FoodAPICore 8 | conference-xplatform-server - Web Deploy 9 | 600 10 | true 11 | MvcControllerEmptyScaffolder 12 | root/Controller 13 | 600 14 | True 15 | False 16 | True 17 | 18 | False 19 | 20 | -------------------------------------------------------------------------------- /server/ASP.NETCore/src/FoodAPICore/Helpers/DynamicExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.ComponentModel; 4 | using System.Dynamic; 5 | using System.Linq; 6 | using System.Threading.Tasks; 7 | 8 | namespace FoodAPICore.Helpers 9 | { 10 | public static class DynamicExtensions 11 | { 12 | public static dynamic ToDynamic(this object value) 13 | { 14 | IDictionary expando = new ExpandoObject(); 15 | 16 | foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(value.GetType())) 17 | expando.Add(property.Name, property.GetValue(value)); 18 | 19 | return expando as ExpandoObject; 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /server/ASP.NETCore/src/FoodAPICore/Helpers/QueryParametersExtensions.cs: -------------------------------------------------------------------------------- 1 | using FoodAPICore.Models; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Threading.Tasks; 6 | 7 | namespace FoodAPICore.Helpers 8 | { 9 | public static class QueryParametersExtensions 10 | { 11 | public static bool HasPrevious(this QueryParameters queryParameters) 12 | { 13 | return (queryParameters.Page > 1); 14 | } 15 | 16 | public static bool HasNext(this QueryParameters queryParameters, int totalCount) 17 | { 18 | return (queryParameters.Page < (int)GetTotalPages(queryParameters, totalCount)); 19 | } 20 | 21 | public static double GetTotalPages(this QueryParameters queryParameters, int totalCount) 22 | { 23 | return Math.Ceiling(totalCount / (double)queryParameters.PageCount); 24 | } 25 | 26 | public static bool HasQuery(this QueryParameters queryParameters) 27 | { 28 | return !String.IsNullOrEmpty(queryParameters.Query); 29 | } 30 | 31 | public static bool IsDescending(this QueryParameters queryParameters) 32 | { 33 | if (!String.IsNullOrEmpty(queryParameters.OrderBy)) 34 | { 35 | return queryParameters.OrderBy.Split(' ').Last().ToLowerInvariant().StartsWith("desc"); 36 | } 37 | return false; 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /server/ASP.NETCore/src/FoodAPICore/Hubs/FoodHub.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.SignalR; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Threading.Tasks; 6 | 7 | namespace FoodAPICore.Hubs 8 | { 9 | public class FoodHub: Hub 10 | { 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /server/ASP.NETCore/src/FoodAPICore/MappingProfiles/FoodMappings.cs: -------------------------------------------------------------------------------- 1 | using AutoMapper; 2 | using FoodAPICore.Dtos; 3 | using FoodAPICore.Models; 4 | 5 | namespace FoodAPICore.MappingProfiles 6 | { 7 | public class FoodMappings : Profile 8 | { 9 | public FoodMappings() 10 | { 11 | CreateMap().ReverseMap(); 12 | CreateMap().ReverseMap(); 13 | CreateMap().ReverseMap(); 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /server/ASP.NETCore/src/FoodAPICore/MappingProfiles/IngredientMappings.cs: -------------------------------------------------------------------------------- 1 | using AutoMapper; 2 | using FoodAPICore.Dtos; 3 | using FoodAPICore.Models; 4 | 5 | namespace FoodAPICore.MappingProfiles 6 | { 7 | public class IngredientMappings : Profile 8 | { 9 | public IngredientMappings() 10 | { 11 | CreateMap().ReverseMap(); 12 | CreateMap().ReverseMap(); 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /server/ASP.NETCore/src/FoodAPICore/Migrations/20180902180236_latest.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore.Migrations; 2 | 3 | namespace FoodAPICore.Migrations 4 | { 5 | public partial class latest : Migration 6 | { 7 | protected override void Up(MigrationBuilder migrationBuilder) 8 | { 9 | migrationBuilder.DropForeignKey( 10 | name: "FK_Ingredient_FoodItems_FoodItemId", 11 | table: "Ingredient"); 12 | 13 | migrationBuilder.DropIndex( 14 | name: "UserNameIndex", 15 | table: "AspNetUsers"); 16 | 17 | migrationBuilder.DropIndex( 18 | name: "RoleNameIndex", 19 | table: "AspNetRoles"); 20 | 21 | migrationBuilder.DropPrimaryKey( 22 | name: "PK_Ingredient", 23 | table: "Ingredient"); 24 | 25 | migrationBuilder.RenameTable( 26 | name: "Ingredient", 27 | newName: "Ingredients"); 28 | 29 | migrationBuilder.RenameIndex( 30 | name: "IX_Ingredient_FoodItemId", 31 | table: "Ingredients", 32 | newName: "IX_Ingredients_FoodItemId"); 33 | 34 | migrationBuilder.AddColumn( 35 | name: "Type", 36 | table: "FoodItems", 37 | nullable: true); 38 | 39 | migrationBuilder.AddPrimaryKey( 40 | name: "PK_Ingredients", 41 | table: "Ingredients", 42 | column: "Id"); 43 | 44 | migrationBuilder.CreateIndex( 45 | name: "UserNameIndex", 46 | table: "AspNetUsers", 47 | column: "NormalizedUserName", 48 | unique: true, 49 | filter: "[NormalizedUserName] IS NOT NULL"); 50 | 51 | migrationBuilder.CreateIndex( 52 | name: "RoleNameIndex", 53 | table: "AspNetRoles", 54 | column: "NormalizedName", 55 | unique: true, 56 | filter: "[NormalizedName] IS NOT NULL"); 57 | 58 | migrationBuilder.AddForeignKey( 59 | name: "FK_AspNetUserTokens_AspNetUsers_UserId", 60 | table: "AspNetUserTokens", 61 | column: "UserId", 62 | principalTable: "AspNetUsers", 63 | principalColumn: "Id", 64 | onDelete: ReferentialAction.Cascade); 65 | 66 | migrationBuilder.AddForeignKey( 67 | name: "FK_Ingredients_FoodItems_FoodItemId", 68 | table: "Ingredients", 69 | column: "FoodItemId", 70 | principalTable: "FoodItems", 71 | principalColumn: "Id", 72 | onDelete: ReferentialAction.Restrict); 73 | } 74 | 75 | protected override void Down(MigrationBuilder migrationBuilder) 76 | { 77 | migrationBuilder.DropForeignKey( 78 | name: "FK_AspNetUserTokens_AspNetUsers_UserId", 79 | table: "AspNetUserTokens"); 80 | 81 | migrationBuilder.DropForeignKey( 82 | name: "FK_Ingredients_FoodItems_FoodItemId", 83 | table: "Ingredients"); 84 | 85 | migrationBuilder.DropIndex( 86 | name: "UserNameIndex", 87 | table: "AspNetUsers"); 88 | 89 | migrationBuilder.DropIndex( 90 | name: "RoleNameIndex", 91 | table: "AspNetRoles"); 92 | 93 | migrationBuilder.DropPrimaryKey( 94 | name: "PK_Ingredients", 95 | table: "Ingredients"); 96 | 97 | migrationBuilder.DropColumn( 98 | name: "Type", 99 | table: "FoodItems"); 100 | 101 | migrationBuilder.RenameTable( 102 | name: "Ingredients", 103 | newName: "Ingredient"); 104 | 105 | migrationBuilder.RenameIndex( 106 | name: "IX_Ingredients_FoodItemId", 107 | table: "Ingredient", 108 | newName: "IX_Ingredient_FoodItemId"); 109 | 110 | migrationBuilder.AddPrimaryKey( 111 | name: "PK_Ingredient", 112 | table: "Ingredient", 113 | column: "Id"); 114 | 115 | migrationBuilder.CreateIndex( 116 | name: "UserNameIndex", 117 | table: "AspNetUsers", 118 | column: "NormalizedUserName", 119 | unique: true); 120 | 121 | migrationBuilder.CreateIndex( 122 | name: "RoleNameIndex", 123 | table: "AspNetRoles", 124 | column: "NormalizedName", 125 | unique: true); 126 | 127 | migrationBuilder.AddForeignKey( 128 | name: "FK_Ingredient_FoodItems_FoodItemId", 129 | table: "Ingredient", 130 | column: "FoodItemId", 131 | principalTable: "FoodItems", 132 | principalColumn: "Id", 133 | onDelete: ReferentialAction.Restrict); 134 | } 135 | } 136 | } 137 | -------------------------------------------------------------------------------- /server/ASP.NETCore/src/FoodAPICore/Models/QueryParameters.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | 6 | namespace FoodAPICore.Models 7 | { 8 | public class QueryParameters 9 | { 10 | private const int maxPageCount = 50; 11 | public int Page { get; set; } = 1; 12 | 13 | private int _pageCount = maxPageCount; 14 | public int PageCount 15 | { 16 | get { return _pageCount; } 17 | set { _pageCount = (value > maxPageCount) ? maxPageCount : value; } 18 | } 19 | 20 | public string Query { get; set; } 21 | 22 | public string OrderBy { get; set; } = "Name"; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /server/ASP.NETCore/src/FoodAPICore/Program.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Hosting; 2 | using Microsoft.Extensions.Logging; 3 | using System; 4 | using FoodAPICore.Entities; 5 | using Microsoft.Extensions.DependencyInjection; 6 | using FoodAPICore.Services; 7 | using Microsoft.Extensions.Hosting; 8 | 9 | namespace FoodAPICore 10 | { 11 | public class Program 12 | { 13 | public static void Main(string[] args) 14 | { 15 | var host = CreateHostBuilder(args).Build(); 16 | 17 | // Initializes db. 18 | using (var scope = host.Services.CreateScope()) 19 | { 20 | var services = scope.ServiceProvider; 21 | try 22 | { 23 | var context = services.GetRequiredService(); 24 | var dbInitializer = services.GetRequiredService(); 25 | dbInitializer.EnsureSeedData(context).GetAwaiter().GetResult(); 26 | } 27 | catch (Exception ex) 28 | { 29 | var logger = services.GetRequiredService>(); 30 | logger.LogError(ex, "An error occurred while seeding the database."); 31 | } 32 | } 33 | 34 | host.Run(); 35 | } 36 | 37 | public static IHostBuilder CreateHostBuilder(string[] args) => 38 | Host.CreateDefaultBuilder(args) 39 | .ConfigureWebHostDefaults(webBuilder => 40 | { 41 | webBuilder.UseStartup(); 42 | }); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /server/ASP.NETCore/src/FoodAPICore/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "http://json.schemastore.org/launchsettings.json", 3 | "iisSettings": { 4 | "windowsAuthentication": false, 5 | "anonymousAuthentication": true, 6 | "iisExpress": { 7 | "applicationUrl": "http://localhost:53206", 8 | "sslPort": 44397 9 | } 10 | }, 11 | "profiles": { 12 | "IIS Express": { 13 | "commandName": "IISExpress", 14 | "launchBrowser": true, 15 | "launchUrl": "swagger", 16 | "environmentVariables": { 17 | "ASPNETCORE_ENVIRONMENT": "Development" 18 | } 19 | }, 20 | "FoodAPICore": { 21 | "commandName": "Project", 22 | "launchBrowser": true, 23 | "launchUrl": "swagger", 24 | "applicationUrl": "https://localhost:5001;http://localhost:5000", 25 | "environmentVariables": { 26 | "ASPNETCORE_ENVIRONMENT": "Development" 27 | } 28 | } 29 | } 30 | } -------------------------------------------------------------------------------- /server/ASP.NETCore/src/FoodAPICore/Repositories/Food/FoodRepository.cs: -------------------------------------------------------------------------------- 1 | using FoodAPICore.Entities; 2 | using FoodAPICore.Helpers; 3 | using FoodAPICore.Models; 4 | using Microsoft.EntityFrameworkCore; 5 | using System; 6 | using System.Collections.Generic; 7 | using System.Linq; 8 | using System.Linq.Dynamic.Core; 9 | 10 | namespace FoodAPICore.Repositories.Food 11 | { 12 | public class FoodRepository : IFoodRepository 13 | { 14 | private readonly FoodDbContext _foodDbContext; 15 | 16 | public FoodRepository(FoodDbContext foodDbContext) 17 | { 18 | _foodDbContext = foodDbContext; 19 | } 20 | 21 | public FoodItem GetSingle(Guid id) 22 | { 23 | return _foodDbContext.FoodItems.FirstOrDefault(x => x.Id == id); 24 | } 25 | 26 | public void Add(FoodItem item) 27 | { 28 | _foodDbContext.FoodItems.Add(item); 29 | } 30 | 31 | public void Delete(Guid id) 32 | { 33 | FoodItem foodItem = _foodDbContext 34 | .FoodItems 35 | .Include(x => x.Ingredients).FirstOrDefault(x => x.Id == id); 36 | 37 | foreach (Ingredient ingredient in foodItem.Ingredients) 38 | { 39 | _foodDbContext.Ingredients.Remove(ingredient); 40 | } 41 | 42 | _foodDbContext.FoodItems.Remove(foodItem); 43 | } 44 | 45 | public void Update(FoodItem item) 46 | { 47 | _foodDbContext.FoodItems.Update(item); 48 | } 49 | 50 | public IQueryable GetAll(QueryParameters queryParameters) 51 | { 52 | IQueryable _allItems = _foodDbContext.FoodItems.OrderBy(queryParameters.OrderBy, 53 | queryParameters.IsDescending()); 54 | 55 | if (queryParameters.HasQuery()) 56 | { 57 | _allItems = _allItems 58 | .Where(x => x.Calories.ToString().Contains(queryParameters.Query.ToLowerInvariant()) 59 | || x.Name.ToLowerInvariant().Contains(queryParameters.Query.ToLowerInvariant())); 60 | } 61 | 62 | return _allItems 63 | .Skip(queryParameters.PageCount * (queryParameters.Page - 1)) 64 | .Take(queryParameters.PageCount); 65 | } 66 | 67 | public int Count() 68 | { 69 | return _foodDbContext.FoodItems.Count(); 70 | } 71 | 72 | public bool Save() 73 | { 74 | return (_foodDbContext.SaveChanges() >= 0); 75 | } 76 | 77 | public ICollection GetRandomMeal() 78 | { 79 | List toReturn = new List(); 80 | 81 | toReturn.Add(GetRandomItem("Starter")); 82 | toReturn.Add(GetRandomItem("Main")); 83 | toReturn.Add(GetRandomItem("Dessert")); 84 | 85 | return toReturn; 86 | } 87 | 88 | private FoodItem GetRandomItem(string type) 89 | { 90 | return _foodDbContext.FoodItems 91 | .Where(x => x.Type == type) 92 | .OrderBy(o => Guid.NewGuid()) 93 | .FirstOrDefault(); 94 | } 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /server/ASP.NETCore/src/FoodAPICore/Repositories/IFoodRepository.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using FoodAPICore.Models; 3 | using System; 4 | using System.Linq; 5 | 6 | namespace FoodAPICore.Repositories 7 | { 8 | public interface IFoodRepository 9 | { 10 | FoodItem GetSingle(Guid id); 11 | void Add(FoodItem item); 12 | void Delete(Guid id); 13 | void Update(FoodItem item); 14 | IQueryable GetAll(QueryParameters queryParameters); 15 | 16 | ICollection GetRandomMeal(); 17 | int Count(); 18 | 19 | bool Save(); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /server/ASP.NETCore/src/FoodAPICore/Repositories/IIngredientRepository.cs: -------------------------------------------------------------------------------- 1 | using FoodAPICore.Models; 2 | using System; 3 | using System.Linq; 4 | 5 | namespace FoodAPICore.Repositories 6 | { 7 | public interface IIngredientRepository 8 | { 9 | Ingredient GetSingle(Guid id); 10 | void Add(Ingredient item); 11 | void Delete(Guid id); 12 | void Update(Ingredient item); 13 | IQueryable GetAll(); 14 | int Count(); 15 | 16 | bool Save(); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /server/ASP.NETCore/src/FoodAPICore/Repositories/Ingredient/IngredientRepository.cs: -------------------------------------------------------------------------------- 1 | using FoodAPICore.Entities; 2 | using FoodAPICore.Models; 3 | using System; 4 | using System.Linq; 5 | 6 | namespace FoodAPICore.Repositories 7 | { 8 | public class IngredientRepository : IIngredientRepository 9 | { 10 | FoodDbContext _foodDbContext; 11 | 12 | public IngredientRepository(FoodDbContext foodDbContext) 13 | { 14 | _foodDbContext = foodDbContext; 15 | } 16 | 17 | public void Add(Ingredient item) 18 | { 19 | _foodDbContext.Ingredients.Add(item); 20 | } 21 | 22 | public int Count() 23 | { 24 | return _foodDbContext.Ingredients.Count(); 25 | } 26 | 27 | public void Delete(Guid id) 28 | { 29 | Ingredient toRemove = GetSingle(id); 30 | _foodDbContext.Ingredients.Remove(toRemove); 31 | } 32 | 33 | public IQueryable GetAll() 34 | { 35 | return _foodDbContext.Ingredients; 36 | } 37 | 38 | public Ingredient GetSingle(Guid id) 39 | { 40 | return _foodDbContext.Ingredients.FirstOrDefault(x => x.Id == id); 41 | } 42 | 43 | public bool Save() 44 | { 45 | return (_foodDbContext.SaveChanges() >= 0); 46 | } 47 | 48 | public void Update(Ingredient item) 49 | { 50 | _foodDbContext.Ingredients.Update(item); 51 | } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /server/ASP.NETCore/src/FoodAPICore/Services/EnsureDatabaseDataService.cs: -------------------------------------------------------------------------------- 1 | using FoodAPICore.Entities; 2 | using FoodAPICore.Models; 3 | using System; 4 | using System.Threading.Tasks; 5 | 6 | namespace FoodAPICore.Services 7 | { 8 | public class EnsureDatabaseDataService : IEnsureDatabaseDataService 9 | { 10 | public async Task EnsureSeedData(FoodDbContext context) 11 | { 12 | context.Database.EnsureCreated(); 13 | 14 | context.FoodItems.Add(new FoodItem() { Calories = 1000, Name = "Lasagne", Type="Main", Created = DateTime.Now }); 15 | context.FoodItems.Add(new FoodItem() { Calories = 1100, Name = "Hamburger", Type = "Main", Created = DateTime.Now }); 16 | context.FoodItems.Add(new FoodItem() { Calories = 1200, Name = "Spaghetti", Type = "Main", Created = DateTime.Now }); 17 | context.FoodItems.Add(new FoodItem() { Calories = 1300, Name = "Pizza", Type = "Main", Created = DateTime.Now }); 18 | 19 | await context.SaveChangesAsync(); 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /server/ASP.NETCore/src/FoodAPICore/Services/IEnsureDatabaseDataService.cs: -------------------------------------------------------------------------------- 1 | using FoodAPICore.Entities; 2 | using Microsoft.AspNetCore.Identity; 3 | using Microsoft.Extensions.Logging; 4 | using System.Threading.Tasks; 5 | 6 | namespace FoodAPICore.Services 7 | { 8 | public interface IEnsureDatabaseDataService 9 | { 10 | Task EnsureSeedData(FoodDbContext context); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /server/ASP.NETCore/src/FoodAPICore/Startup.cs: -------------------------------------------------------------------------------- 1 | using FoodAPICore.Repositories.Food; 2 | using FoodAPICore.Repositories; 3 | using Microsoft.AspNetCore.Builder; 4 | using Microsoft.AspNetCore.Diagnostics; 5 | using Microsoft.AspNetCore.Hosting; 6 | using Microsoft.Extensions.Configuration; 7 | using Microsoft.Extensions.DependencyInjection; 8 | using Microsoft.Extensions.Logging; 9 | using Microsoft.AspNetCore.Http; 10 | using FoodAPICore.Entities; 11 | using Microsoft.EntityFrameworkCore; 12 | using FoodAPICore.Services; 13 | using Microsoft.AspNetCore.Mvc; 14 | using Microsoft.AspNetCore.Mvc.Routing; 15 | using Microsoft.AspNetCore.Mvc.Infrastructure; 16 | using FoodAPICore.Hubs; 17 | using AutoMapper; 18 | using FoodAPICore.MappingProfiles; 19 | using Microsoft.Extensions.Hosting; 20 | using Microsoft.OpenApi.Models; 21 | 22 | namespace FoodAPICore 23 | { 24 | public class Startup 25 | { 26 | public IConfiguration Configuration { get; } 27 | 28 | public Startup(IConfiguration configuration) 29 | { 30 | Configuration = configuration; 31 | } 32 | 33 | // This method gets called by the runtime. Use this method to add services to the container. 34 | // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940 35 | public void ConfigureServices(IServiceCollection services) 36 | { 37 | services.AddOptions(); 38 | 39 | services.AddCors(options => 40 | { 41 | options.AddPolicy("AllowAllOrigins", 42 | builder => 43 | { 44 | builder 45 | .WithOrigins("https://conference-xplatform-client.azurewebsites.net", "http://localhost:4200", "https://localhost:4200") 46 | .AllowAnyHeader() 47 | .AllowAnyMethod() 48 | .AllowCredentials(); 49 | }); 50 | }); 51 | 52 | services.AddDbContext(opt => opt.UseInMemoryDatabase("FoodDatabase")); 53 | // services.AddDbContext(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); 54 | 55 | services.AddScoped(); 56 | services.AddScoped(); 57 | services.AddScoped(); 58 | services.AddSingleton(); 59 | 60 | services.AddRouting(options => options.LowercaseUrls = true); 61 | 62 | services.AddScoped(x => 63 | { 64 | var actionContext = x.GetRequiredService().ActionContext; 65 | var factory = x.GetRequiredService(); 66 | return factory.GetUrlHelper(actionContext); 67 | }); 68 | 69 | services.AddSignalR(); 70 | 71 | services.AddControllers() 72 | .AddNewtonsoftJson(options => options.UseCamelCasing(true)) 73 | .SetCompatibilityVersion(CompatibilityVersion.Version_3_0); 74 | 75 | services.AddSwaggerGen(c => 76 | { 77 | c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" }); 78 | }); 79 | 80 | services.AddAutoMapper(new[] { typeof(FoodMappings), typeof(IngredientMappings) }); 81 | } 82 | 83 | // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 84 | public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory) 85 | { 86 | if (env.IsDevelopment()) 87 | { 88 | app.UseDeveloperExceptionPage(); 89 | } 90 | else 91 | { 92 | app.UseHsts(); 93 | app.UseExceptionHandler(errorApp => 94 | { 95 | errorApp.Run(async context => 96 | { 97 | context.Response.StatusCode = 500; 98 | context.Response.ContentType = "text/plain"; 99 | var errorFeature = context.Features.Get(); 100 | if (errorFeature != null) 101 | { 102 | var logger = loggerFactory.CreateLogger("Global exception logger"); 103 | logger.LogError(500, errorFeature.Error, errorFeature.Error.Message); 104 | } 105 | 106 | await context.Response.WriteAsync("There was an error"); 107 | }); 108 | }); 109 | } 110 | 111 | app.UseHttpsRedirection(); 112 | app.UseRouting(); 113 | app.UseCors("AllowAllOrigins"); 114 | app.UseStaticFiles(); 115 | app.UseDefaultFiles(); 116 | 117 | app.UseEndpoints(endpoints => 118 | { 119 | endpoints.MapControllers(); 120 | endpoints.MapHub("/foodhub"); 121 | }); 122 | 123 | app.UseSwagger(); 124 | app.UseSwaggerUI(c => 125 | { 126 | c.SwaggerEndpoint("/swagger/v1/swagger.json", "FoodAPICore V1"); 127 | }); 128 | } 129 | } 130 | } 131 | -------------------------------------------------------------------------------- /server/ASP.NETCore/src/FoodAPICore/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "ConnectionStrings": { 3 | "DefaultConnection": "Server=.\\SQLEXPRESS;Database=FoodAPIASPNETCore;Trusted_Connection=True;" 4 | }, 5 | "Logging": { 6 | "LogLevel": { 7 | "Default": "Debug", 8 | "System": "Information", 9 | "Microsoft": "Information" 10 | } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /server/ASP.NETCore/src/FoodAPICore/web.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | --------------------------------------------------------------------------------