Repository: arjunyel/angular-spacex-graphql-codegen Branch: master Commit: 6b7bfaf0138f Files: 46 Total size: 68.2 KB Directory structure: gitextract_i8_mwi3q/ ├── .editorconfig ├── .gitignore ├── LICENSE ├── README.md ├── angular.json ├── apollo.config.js ├── browserslist ├── codegen.yml ├── e2e/ │ ├── protractor.conf.js │ ├── src/ │ │ ├── app.e2e-spec.ts │ │ └── app.po.ts │ └── tsconfig.json ├── karma.conf.js ├── package.json ├── src/ │ ├── app/ │ │ ├── app-routing.module.ts │ │ ├── app.component.css │ │ ├── app.component.html │ │ ├── app.component.spec.ts │ │ ├── app.component.ts │ │ ├── app.module.ts │ │ ├── graphql.module.ts │ │ ├── launch-details/ │ │ │ ├── launch-details.component.css │ │ │ ├── launch-details.component.html │ │ │ ├── launch-details.component.spec.ts │ │ │ ├── launch-details.component.ts │ │ │ └── launch-details.graphql │ │ ├── launch-list/ │ │ │ ├── launch-list.component.css │ │ │ ├── launch-list.component.html │ │ │ ├── launch-list.component.spec.ts │ │ │ ├── launch-list.component.ts │ │ │ └── launch-list.graphql │ │ ├── relative-time/ │ │ │ ├── relative-time.pipe.spec.ts │ │ │ └── relative-time.pipe.ts │ │ └── services/ │ │ └── spacexGraphql.service.ts │ ├── assets/ │ │ └── .gitkeep │ ├── environments/ │ │ ├── environment.prod.ts │ │ └── environment.ts │ ├── index.html │ ├── main.ts │ ├── polyfills.ts │ ├── styles.css │ └── test.ts ├── tsconfig.app.json ├── tsconfig.json ├── tsconfig.spec.json └── tslint.json ================================================ FILE CONTENTS ================================================ ================================================ FILE: .editorconfig ================================================ # Editor configuration, see https://editorconfig.org root = true [*] charset = utf-8 indent_style = space indent_size = 2 insert_final_newline = true trim_trailing_whitespace = true [*.md] max_line_length = off trim_trailing_whitespace = false ================================================ FILE: .gitignore ================================================ # See http://help.github.com/ignore-files/ for more about ignoring files. # compiled output /dist /tmp /out-tsc # Only exists if Bazel was run /bazel-out # dependencies /node_modules # profiling files chrome-profiler-events*.json speed-measure-plugin*.json # IDEs and editors /.idea .project .classpath .c9/ *.launch .settings/ *.sublime-workspace # IDE - VSCode .vscode/* !.vscode/settings.json !.vscode/tasks.json !.vscode/launch.json !.vscode/extensions.json .history/* # misc /.sass-cache /connect.lock /coverage /libpeerconnection.log npm-debug.log yarn-error.log testem.log /typings # System Files .DS_Store Thumbs.db ================================================ FILE: LICENSE ================================================ This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. For more information, please refer to ================================================ FILE: README.md ================================================ # Angular Spacex Graphql Codegen ## Mission Our goal is to make an Angular app with a list of the past SpaceX launches along with an associated details page. Data is provided via the [SpaceX GraphQL API](https://medium.com/open-graphql/launching-spacex-graphql-api-b3d7029086e0) and Angular services are generated via [GraphQL Code Generator](https://graphql-code-generator.com/). We use [Apollo Angular](https://www.apollographql.com/docs/angular/) to access data from the frontend. The API is free so please be nice and don't abuse it. ## End Result ![List view](list-example.jpg) ![Details view](details-example.jpg) ## Steps 1. Generate a new angular application with routing ```bash ng new angular-spacex-graphql-codegen --routing=true --style=css ``` Make sure to delete the default template in `src/app/app.component.html` 1. Install the [Apollo VS Code plugin](https://marketplace.visualstudio.com/items?itemName=apollographql.vscode-apollo) and in the root of the project add `apollo.config.js` ```javascript module.exports = { client: { service: { name: 'angular-spacex-graphql-codegen', url: 'https://api.spacex.land/graphql/' } } }; ``` This points the extension at the SpaceX GraphQL API so we get autocomplete, type information, and other cool features in GraphQL files. You may need to restart VS Code. 1. Generate our two components: ```bash ng g component launch-list --changeDetection=OnPush ``` ```bash ng g component launch-details --changeDetection=OnPush ``` Because our generated services use observables we choose OnPush change detection for the best performance. 1. In `src/app/app-routing.module.ts` we setup the routing: ```typescript import { LaunchListComponent } from './launch-list/launch-list.component'; import { LaunchDetailsComponent } from './launch-details/launch-details.component'; const routes: Routes = [ { path: '', component: LaunchListComponent }, { path: ':id', component: LaunchDetailsComponent } ]; ``` 1. Each component will have its own data requirments so we co-locate our graphql query files next to them ```graphql # src/app/launch-list/launch-list.graphql query pastLaunchesList($limit: Int!) { launchesPast(limit: $limit) { id mission_name links { flickr_images mission_patch_small } rocket { rocket_name } launch_date_utc } } ``` ```graphql # src/app/launch-details/launch-details.graphql query launchDetails($id: ID!) { launch(id: $id) { id mission_name details links { flickr_images mission_patch } } } ``` Note the first line: `query launchDetails($id: ID!)` When we generate the Angular service the query name is turned into PascalCase and GQL is appended to the end, so the service name for the launch details would be LaunchDetailsGQL. Also in the first line we define any variables we'll need to pass into the query. Please note it's import to include id in the query return so apollo can cache the data. 1. We add [Apollo Angular](https://www.apollographql.com/docs/angular/) to our app with `ng add apollo-angular`. In `src/app/graphql.module.ts` we set our API url `const uri = 'https://api.spacex.land/graphql/';`. 1. Install Graphql Code Generator and the needed plugins `npm i --save-dev @graphql-codegen/cli @graphql-codegen/typescript @graphql-codegen/typescript-apollo-angular @graphql-codegen/typescript-operations` 1. In the root of the project create a `codegen.yml` file: ```yml # Where to get schema data schema: - https://api.spacex.land/graphql/ # The client side queries to turn into services documents: - src/**/*.graphql # Where to output the services and the list of plugins generates: ./src/app/services/spacexGraphql.service.ts: plugins: - typescript - typescript-operations - typescript-apollo-angular ``` 1. In package.json add a script `"codegen": "gql-gen"` then `npm run codegen` to generate the Angular Services. 1. To make it look nice we add Angular Material `ng add @angular/material` then in the `app.module.ts` we import the card module and add to the imports array: `import { MatCardModule } from '@angular/material/card';` 1. Lets start with the list of past launches displayed on the screen: ```typescript import { map } from 'rxjs/operators'; import { PastLaunchesListGQL } from '../services/spacexGraphql.service'; export class LaunchListComponent { constructor(private readonly pastLaunchesService: PastLaunchesListGQL) {} // Please be careful to not fetch too much, but this amount lets us see lazy loading imgs in action pastLaunches$ = this.pastLaunchesService .fetch({ limit: 30 }) // Here we extract our query data, we can also get info like errors or loading state from res .pipe(map((res) => res.data.launchesPast)); } ``` ```html
Mission patch of {{ launch.mission_name }} {{ launch.mission_name }} {{ launch.rocket.rocket_name }} Photo of {{ launch.mission_name }}
``` Notice the cool addition of [lazy loading images](https://web.dev/native-lazy-loading), if you emulate a mobile device in Chrome and fetch enough launches you should see the images lazy load while you scroll! To make it look nice we add CSS Grid ```css .container { padding-top: 20px; display: grid; grid-gap: 30px; grid-template-columns: repeat(auto-fill, 350px); justify-content: center; } .mat-card { cursor: pointer; } ``` 1. Next we make the details page for a launch, we get the id from the route params and pass that to our service ```typescript import { ActivatedRoute } from '@angular/router'; import { map, switchMap } from 'rxjs/operators'; import { LaunchDetailsGQL } from '../services/spacexGraphql.service'; export class LaunchDetailsComponent { constructor( private readonly route: ActivatedRoute, private readonly launchDetailsService: LaunchDetailsGQL ) {} launchDetails$ = this.route.paramMap.pipe( map((params) => params.get('id') as string), switchMap((id) => this.launchDetailsService.fetch({ id })), map((res) => res.data.launch) ); } ``` The HTML looks very similar to the list of launches ```html
{{ launchDetails.mission_name }} Mission patch of {{ launchDetails.mission_name }}

{{ launchDetails.details }}

Picture of {{ launchDetails.mission_name }}
``` Finally we add CSS Grid for the pictures ```css .photo-grid { padding-top: 30px; display: grid; grid-gap: 10px; grid-template-columns: repeat(auto-fill, 300px); justify-content: center; } ``` 1. `npm start`, navigate to `http://localhost:4200/`, and it should work! ### Extra Credit: Relative launch times Thanks to the new builtin [relative time formating](https://v8.dev/features/intl-relativetimeformat) in V8, we can add `launched x days ago` 1. Generate the pipe: `ng g pipe relative-time --module=app.module --flat=false` 1. The pipe takes in the UTC time and returns a formatted string ```typescript import { Pipe, PipeTransform } from '@angular/core'; const milliSecondsInDay = 1000 * 3600 * 24; // Cast as any because typescript typing haven't updated yet const rtf = new (Intl as any).RelativeTimeFormat('en'); @Pipe({ name: 'relativeTime' }) export class RelativeTimePipe implements PipeTransform { transform(utcTime: string): string { const diffInMillicseconds = new Date(utcTime).getTime() - new Date().getTime(); const diffInDays = Math.round(diffInMillicseconds / milliSecondsInDay); return rtf.format(diffInDays, 'day'); } } ``` 1. Add the pipe to our launch card in src/app/launch-list/launch-list.component.html ```html {{ launch.rocket.rocket_name }} - launched {{ launch.launch_date_utc | relativeTime }} ``` ================================================ FILE: angular.json ================================================ { "$schema": "./node_modules/@angular/cli/lib/config/schema.json", "version": 1, "newProjectRoot": "projects", "projects": { "angular-spacex-graphql-codegen": { "projectType": "application", "schematics": {}, "root": "", "sourceRoot": "src", "prefix": "app", "architect": { "build": { "builder": "@angular-devkit/build-angular:browser", "options": { "outputPath": "dist/angular-spacex-graphql-codegen", "index": "src/index.html", "main": "src/main.ts", "polyfills": "src/polyfills.ts", "tsConfig": "tsconfig.app.json", "aot": false, "assets": [ "src/favicon.ico", "src/assets" ], "styles": [ "./node_modules/@angular/material/prebuilt-themes/indigo-pink.css", "src/styles.css" ], "scripts": [] }, "configurations": { "production": { "fileReplacements": [ { "replace": "src/environments/environment.ts", "with": "src/environments/environment.prod.ts" } ], "optimization": true, "outputHashing": "all", "sourceMap": false, "extractCss": true, "namedChunks": false, "aot": true, "extractLicenses": true, "vendorChunk": false, "buildOptimizer": true, "budgets": [ { "type": "initial", "maximumWarning": "2mb", "maximumError": "5mb" }, { "type": "anyComponentStyle", "maximumWarning": "6kb", "maximumError": "10kb" } ] } } }, "serve": { "builder": "@angular-devkit/build-angular:dev-server", "options": { "browserTarget": "angular-spacex-graphql-codegen:build" }, "configurations": { "production": { "browserTarget": "angular-spacex-graphql-codegen:build:production" } } }, "extract-i18n": { "builder": "@angular-devkit/build-angular:extract-i18n", "options": { "browserTarget": "angular-spacex-graphql-codegen:build" } }, "test": { "builder": "@angular-devkit/build-angular:karma", "options": { "main": "src/test.ts", "polyfills": "src/polyfills.ts", "tsConfig": "tsconfig.spec.json", "karmaConfig": "karma.conf.js", "assets": [ "src/favicon.ico", "src/assets" ], "styles": [ "./node_modules/@angular/material/prebuilt-themes/indigo-pink.css", "src/styles.css" ], "scripts": [] } }, "lint": { "builder": "@angular-devkit/build-angular:tslint", "options": { "tsConfig": [ "tsconfig.app.json", "tsconfig.spec.json", "e2e/tsconfig.json" ], "exclude": [ "**/node_modules/**" ] } }, "e2e": { "builder": "@angular-devkit/build-angular:protractor", "options": { "protractorConfig": "e2e/protractor.conf.js", "devServerTarget": "angular-spacex-graphql-codegen:serve" }, "configurations": { "production": { "devServerTarget": "angular-spacex-graphql-codegen:serve:production" } } } } } }, "defaultProject": "angular-spacex-graphql-codegen" } ================================================ FILE: apollo.config.js ================================================ module.exports = { client: { service: { name: 'angular-spacex-graphql-codegen', url: 'https://api.spacex.land/graphql/' } } }; ================================================ FILE: browserslist ================================================ # This file is used by the build system to adjust CSS and JS output to support the specified browsers below. # For additional information regarding the format and rule options, please see: # https://github.com/browserslist/browserslist#queries # You can see what browsers were selected by your queries by running: # npx browserslist > 0.5% last 2 versions Firefox ESR not dead not IE 9-11 # For IE 9-11 support, remove 'not'. ================================================ FILE: codegen.yml ================================================ # Where to get schema data schema: - https://api.spacex.land/graphql/ # The client side queries to turn into services documents: - src/**/*.graphql # Where to output the services and the list of plugins generates: ./src/app/services/spacexGraphql.service.ts: plugins: - typescript - typescript-operations - typescript-apollo-angular ================================================ FILE: e2e/protractor.conf.js ================================================ // @ts-check // Protractor configuration file, see link for more information // https://github.com/angular/protractor/blob/master/lib/config.ts const { SpecReporter } = require('jasmine-spec-reporter'); /** * @type { import("protractor").Config } */ exports.config = { allScriptsTimeout: 11000, specs: [ './src/**/*.e2e-spec.ts' ], capabilities: { 'browserName': 'chrome' }, directConnect: true, baseUrl: 'http://localhost:4200/', framework: 'jasmine', jasmineNodeOpts: { showColors: true, defaultTimeoutInterval: 30000, print: function() {} }, onPrepare() { require('ts-node').register({ project: require('path').join(__dirname, './tsconfig.json') }); jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } })); } }; ================================================ FILE: e2e/src/app.e2e-spec.ts ================================================ import { AppPage } from './app.po'; import { browser, logging } from 'protractor'; describe('workspace-project App', () => { let page: AppPage; beforeEach(() => { page = new AppPage(); }); it('should display welcome message', () => { page.navigateTo(); expect(page.getTitleText()).toEqual('angular-spacex-graphql-codegen app is running!'); }); afterEach(async () => { // Assert that there are no errors emitted from the browser const logs = await browser.manage().logs().get(logging.Type.BROWSER); expect(logs).not.toContain(jasmine.objectContaining({ level: logging.Level.SEVERE, } as logging.Entry)); }); }); ================================================ FILE: e2e/src/app.po.ts ================================================ import { browser, by, element } from 'protractor'; export class AppPage { navigateTo() { return browser.get(browser.baseUrl) as Promise; } getTitleText() { return element(by.css('app-root .content span')).getText() as Promise; } } ================================================ FILE: e2e/tsconfig.json ================================================ { "extends": "../tsconfig.json", "compilerOptions": { "outDir": "../out-tsc/e2e", "module": "commonjs", "target": "es5", "types": [ "jasmine", "jasminewd2", "node" ] } } ================================================ FILE: karma.conf.js ================================================ // Karma configuration file, see link for more information // https://karma-runner.github.io/1.0/config/configuration-file.html module.exports = function (config) { config.set({ basePath: '', frameworks: ['jasmine', '@angular-devkit/build-angular'], plugins: [ require('karma-jasmine'), require('karma-chrome-launcher'), require('karma-jasmine-html-reporter'), require('karma-coverage-istanbul-reporter'), require('@angular-devkit/build-angular/plugins/karma') ], client: { clearContext: false // leave Jasmine Spec Runner output visible in browser }, coverageIstanbulReporter: { dir: require('path').join(__dirname, './coverage/angular-spacex-graphql-codegen'), reports: ['html', 'lcovonly', 'text-summary'], fixWebpackSourcePaths: true }, reporters: ['progress', 'kjhtml'], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, browsers: ['Chrome'], singleRun: false, restartOnFileChange: true }); }; ================================================ FILE: package.json ================================================ { "name": "angular-spacex-graphql-codegen", "version": "0.0.0", "scripts": { "ng": "ng", "start": "ng serve --aot", "build": "ng build", "test": "ng test", "lint": "ng lint", "e2e": "ng e2e", "codegen": "gql-gen" }, "private": true, "dependencies": { "@angular/animations": "~8.2.5", "@angular/cdk": "~8.2.0", "@angular/common": "~8.2.5", "@angular/compiler": "~8.2.5", "@angular/core": "~8.2.5", "@angular/forms": "~8.2.5", "@angular/material": "^8.2.0", "@angular/platform-browser": "~8.2.5", "@angular/platform-browser-dynamic": "~8.2.5", "@angular/router": "~8.2.5", "apollo-angular": "^1.7.0", "apollo-angular-link-http": "^1.8.0", "apollo-cache-inmemory": "^1.6.3", "apollo-client": "^2.6.4", "apollo-link": "^1.2.13", "graphql": "^14.5.5", "graphql-tag": "^2.10.1", "hammerjs": "^2.0.8", "rxjs": "~6.4.0", "tslib": "^1.10.0", "zone.js": "~0.9.1" }, "devDependencies": { "@angular-devkit/build-angular": "~0.803.4", "@angular/cli": "~8.3.4", "@angular/compiler-cli": "~8.2.5", "@angular/language-service": "~8.2.5", "@graphql-codegen/cli": "^1.7.0", "@graphql-codegen/typescript": "^1.7.0", "@graphql-codegen/typescript-apollo-angular": "^1.7.0", "@graphql-codegen/typescript-operations": "^1.7.0", "@types/jasmine": "~3.3.8", "@types/jasminewd2": "~2.0.3", "@types/node": "~8.9.4", "codelyzer": "^5.0.0", "jasmine-core": "~3.4.0", "jasmine-spec-reporter": "~4.2.1", "karma": "~4.1.0", "karma-chrome-launcher": "~2.2.0", "karma-coverage-istanbul-reporter": "~2.0.1", "karma-jasmine": "~2.0.1", "karma-jasmine-html-reporter": "^1.4.0", "protractor": "~5.4.0", "ts-node": "~7.0.0", "tslint": "~5.15.0", "typescript": "~3.5.3" } } ================================================ FILE: src/app/app-routing.module.ts ================================================ import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { LaunchListComponent } from './launch-list/launch-list.component'; import { LaunchDetailsComponent } from './launch-details/launch-details.component'; const routes: Routes = [ { path: '', component: LaunchListComponent }, { path: ':id', component: LaunchDetailsComponent } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule {} ================================================ FILE: src/app/app.component.css ================================================ ================================================ FILE: src/app/app.component.html ================================================ ================================================ FILE: src/app/app.component.spec.ts ================================================ import { TestBed, async } from '@angular/core/testing'; import { RouterTestingModule } from '@angular/router/testing'; import { AppComponent } from './app.component'; describe('AppComponent', () => { beforeEach(async(() => { TestBed.configureTestingModule({ imports: [ RouterTestingModule ], declarations: [ AppComponent ], }).compileComponents(); })); it('should create the app', () => { const fixture = TestBed.createComponent(AppComponent); const app = fixture.debugElement.componentInstance; expect(app).toBeTruthy(); }); it(`should have as title 'angular-spacex-graphql-codegen'`, () => { const fixture = TestBed.createComponent(AppComponent); const app = fixture.debugElement.componentInstance; expect(app.title).toEqual('angular-spacex-graphql-codegen'); }); it('should render title', () => { const fixture = TestBed.createComponent(AppComponent); fixture.detectChanges(); const compiled = fixture.debugElement.nativeElement; expect(compiled.querySelector('.content span').textContent).toContain('angular-spacex-graphql-codegen app is running!'); }); }); ================================================ FILE: src/app/app.component.ts ================================================ import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'angular-spacex-graphql-codegen'; test = new Date(); } ================================================ FILE: src/app/app.module.ts ================================================ import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { LaunchListComponent } from './launch-list/launch-list.component'; import { LaunchDetailsComponent } from './launch-details/launch-details.component'; import { GraphQLModule } from './graphql.module'; import { HttpClientModule } from '@angular/common/http'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { MatCardModule } from '@angular/material/card'; import { RelativeTimePipe } from './relative-time/relative-time.pipe'; @NgModule({ declarations: [AppComponent, LaunchListComponent, LaunchDetailsComponent, RelativeTimePipe], imports: [ BrowserModule, AppRoutingModule, GraphQLModule, HttpClientModule, BrowserAnimationsModule, MatCardModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule {} ================================================ FILE: src/app/graphql.module.ts ================================================ import {NgModule} from '@angular/core'; import {ApolloModule, APOLLO_OPTIONS} from 'apollo-angular'; import {HttpLinkModule, HttpLink} from 'apollo-angular-link-http'; import {InMemoryCache} from 'apollo-cache-inmemory'; const uri = 'https://api.spacex.land/graphql/'; // <-- add the URL of the GraphQL server here export function createApollo(httpLink: HttpLink) { return { link: httpLink.create({uri}), cache: new InMemoryCache(), }; } @NgModule({ exports: [ApolloModule, HttpLinkModule], providers: [ { provide: APOLLO_OPTIONS, useFactory: createApollo, deps: [HttpLink], }, ], }) export class GraphQLModule {} ================================================ FILE: src/app/launch-details/launch-details.component.css ================================================ .photo-grid { padding-top: 30px; display: grid; grid-gap: 10px; grid-template-columns: repeat(auto-fill, 300px); justify-content: center; } ================================================ FILE: src/app/launch-details/launch-details.component.html ================================================
{{ launchDetails.mission_name }} Mission patch of {{ launchDetails.mission_name }}

{{ launchDetails.details }}

Picture of {{ launchDetails.mission_name }}
================================================ FILE: src/app/launch-details/launch-details.component.spec.ts ================================================ import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { LaunchDetailsComponent } from './launch-details.component'; describe('LaunchDetailsComponent', () => { let component: LaunchDetailsComponent; let fixture: ComponentFixture; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ LaunchDetailsComponent ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(LaunchDetailsComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); }); ================================================ FILE: src/app/launch-details/launch-details.component.ts ================================================ import { Component, ChangeDetectionStrategy } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { map, switchMap } from 'rxjs/operators'; import { LaunchDetailsGQL } from '../services/spacexGraphql.service'; @Component({ selector: 'app-launch-details', templateUrl: './launch-details.component.html', styleUrls: ['./launch-details.component.css'], changeDetection: ChangeDetectionStrategy.OnPush }) export class LaunchDetailsComponent { constructor( private readonly route: ActivatedRoute, private readonly launchDetailsService: LaunchDetailsGQL ) {} launchDetails$ = this.route.paramMap.pipe( map((params) => params.get('id') as string), switchMap((id) => this.launchDetailsService.fetch({ id })), map((res) => res.data.launch) ); } ================================================ FILE: src/app/launch-details/launch-details.graphql ================================================ # src/app/launch-details/launch-details.frontend.graphql query launchDetails($id: ID!) { launch(id: $id) { id mission_name details links { flickr_images mission_patch } } } ================================================ FILE: src/app/launch-list/launch-list.component.css ================================================ .container { padding-top: 20px; display: grid; grid-gap: 30px; grid-template-columns: repeat(auto-fill, 350px); justify-content: center; } .mat-card { cursor: pointer; } ================================================ FILE: src/app/launch-list/launch-list.component.html ================================================
Mission patch of {{ launch.mission_name }} {{ launch.mission_name }} {{ launch.rocket.rocket_name }} - launched {{ launch.launch_date_utc | relativeTime }} Photo of {{ launch.mission_name }}
================================================ FILE: src/app/launch-list/launch-list.component.spec.ts ================================================ import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { LaunchListComponent } from './launch-list.component'; describe('LaunchListComponent', () => { let component: LaunchListComponent; let fixture: ComponentFixture; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ LaunchListComponent ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(LaunchListComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); }); ================================================ FILE: src/app/launch-list/launch-list.component.ts ================================================ import { Component, ChangeDetectionStrategy } from '@angular/core'; import { map } from 'rxjs/operators'; import { PastLaunchesListGQL } from '../services/spacexGraphql.service'; @Component({ selector: 'app-launch-list', templateUrl: './launch-list.component.html', styleUrls: ['./launch-list.component.css'], changeDetection: ChangeDetectionStrategy.OnPush }) export class LaunchListComponent { constructor(private readonly pastLaunchesService: PastLaunchesListGQL) {} pastLaunches$ = this.pastLaunchesService // Please be care to not fetch too much, but this amount lets us see the img lazy loading in action .fetch({ limit: 30 }) .pipe(map((res) => res.data.launchesPast)); } ================================================ FILE: src/app/launch-list/launch-list.graphql ================================================ # src/app/launch-list/launch-list.graphql query pastLaunchesList($limit: Int!) { launchesPast(limit: $limit) { id mission_name links { flickr_images mission_patch_small } rocket { rocket_name } launch_date_utc } } ================================================ FILE: src/app/relative-time/relative-time.pipe.spec.ts ================================================ import { RelativeTimePipe } from './relative-time.pipe'; describe('RelativeTimePipe', () => { it('create an instance', () => { const pipe = new RelativeTimePipe(); expect(pipe).toBeTruthy(); }); }); ================================================ FILE: src/app/relative-time/relative-time.pipe.ts ================================================ import { Pipe, PipeTransform } from '@angular/core'; const milliSecondsInDay = 1000 * 3600 * 24; // Cast as any because typescript typing haven't updated yet const rtf = new (Intl as any).RelativeTimeFormat('en'); @Pipe({ name: 'relativeTime' }) export class RelativeTimePipe implements PipeTransform { transform(utcTime: string): string { const diffInMillicseconds = new Date(utcTime).getTime() - new Date().getTime(); const diffInDays = Math.round(diffInMillicseconds / milliSecondsInDay); return rtf.format(diffInDays, 'day'); } } ================================================ FILE: src/app/services/spacexGraphql.service.ts ================================================ import gql from 'graphql-tag'; import { Injectable } from '@angular/core'; import * as Apollo from 'apollo-angular'; export type Maybe = T | null; /** All built-in and custom scalars, mapped to their actual values */ export type Scalars = { ID: string, String: string, Boolean: boolean, Int: number, Float: number, Date: any, ObjectID: any, }; export type Address = { __typename?: 'Address', address?: Maybe, city?: Maybe, state?: Maybe, }; export type Capsule = { __typename?: 'Capsule', id?: Maybe, landings?: Maybe, missions?: Maybe>>, original_launch?: Maybe, reuse_count?: Maybe, status?: Maybe, type?: Maybe, dragon?: Maybe, }; export type CapsuleMission = { __typename?: 'CapsuleMission', flight?: Maybe, name?: Maybe, }; export type CapsulesFind = { id?: Maybe, landings?: Maybe, mission?: Maybe, original_launch?: Maybe, reuse_count?: Maybe, status?: Maybe, type?: Maybe, }; export type Core = { __typename?: 'Core', asds_attempts?: Maybe, asds_landings?: Maybe, block?: Maybe, id?: Maybe, missions?: Maybe>>, original_launch?: Maybe, reuse_count?: Maybe, rtls_attempts?: Maybe, rtls_landings?: Maybe, status?: Maybe, water_landing?: Maybe, }; export type CoreMission = { __typename?: 'CoreMission', name?: Maybe, flight?: Maybe, }; export type CoresFind = { asds_attempts?: Maybe, asds_landings?: Maybe, block?: Maybe, id?: Maybe, missions?: Maybe, original_launch?: Maybe, reuse_count?: Maybe, rtls_attempts?: Maybe, rtls_landings?: Maybe, status?: Maybe, water_landing?: Maybe, }; export type Distance = { __typename?: 'Distance', feet?: Maybe, meters?: Maybe, }; export type Dragon = { __typename?: 'Dragon', active?: Maybe, crew_capacity?: Maybe, description?: Maybe, diameter?: Maybe, dry_mass_kg?: Maybe, dry_mass_lb?: Maybe, first_flight?: Maybe, heat_shield?: Maybe, height_w_trunk?: Maybe, id?: Maybe, launch_payload_mass?: Maybe, launch_payload_vol?: Maybe, name?: Maybe, orbit_duration_yr?: Maybe, pressurized_capsule?: Maybe, return_payload_mass?: Maybe, return_payload_vol?: Maybe, sidewall_angle_deg?: Maybe, thrusters?: Maybe>>, trunk?: Maybe, type?: Maybe, wikipedia?: Maybe, }; export type DragonHeatShield = { __typename?: 'DragonHeatShield', dev_partner?: Maybe, material?: Maybe, size_meters?: Maybe, temp_degrees?: Maybe, }; export type DragonPressurizedCapsule = { __typename?: 'DragonPressurizedCapsule', payload_volume?: Maybe, }; export type DragonThrust = { __typename?: 'DragonThrust', amount?: Maybe, fuel_1?: Maybe, fuel_2?: Maybe, pods?: Maybe, thrust?: Maybe, type?: Maybe, }; export type DragonTrunk = { __typename?: 'DragonTrunk', cargo?: Maybe, trunk_volume?: Maybe, }; export type DragonTrunkCargo = { __typename?: 'DragonTrunkCargo', solar_array?: Maybe, unpressurized_cargo?: Maybe, }; export type Force = { __typename?: 'Force', kN?: Maybe, lbf?: Maybe, }; export type HistoriesResult = { __typename?: 'HistoriesResult', result?: Maybe, data?: Maybe>>, }; export type History = { __typename?: 'History', details?: Maybe, event_date_unix?: Maybe, event_date_utc?: Maybe, id?: Maybe, links?: Maybe, title?: Maybe, flight?: Maybe, }; export type HistoryFind = { end?: Maybe, flight_number?: Maybe, id?: Maybe, start?: Maybe, }; export type Info = { __typename?: 'Info', ceo?: Maybe, coo?: Maybe, cto_propulsion?: Maybe, cto?: Maybe, employees?: Maybe, founded?: Maybe, founder?: Maybe, headquarters?: Maybe
, launch_sites?: Maybe, links?: Maybe, name?: Maybe, summary?: Maybe, test_sites?: Maybe, valuation?: Maybe, vehicles?: Maybe, }; export type InfoLinks = { __typename?: 'InfoLinks', elon_twitter?: Maybe, flickr?: Maybe, twitter?: Maybe, website?: Maybe, }; export type Landpad = { __typename?: 'Landpad', attempted_landings?: Maybe, details?: Maybe, full_name?: Maybe, id?: Maybe, landing_type?: Maybe, location?: Maybe, status?: Maybe, successful_landings?: Maybe, wikipedia?: Maybe, }; export type Launch = { __typename?: 'Launch', details?: Maybe, id?: Maybe, is_tentative?: Maybe, launch_date_local?: Maybe, launch_date_unix?: Maybe, launch_date_utc?: Maybe, launch_site?: Maybe, launch_success?: Maybe, launch_year?: Maybe, links?: Maybe, mission_id?: Maybe>>, mission_name?: Maybe, rocket?: Maybe, static_fire_date_unix?: Maybe, static_fire_date_utc?: Maybe, telemetry?: Maybe, tentative_max_precision?: Maybe, upcoming?: Maybe, ships?: Maybe>>, }; export type LaunchesPastResult = { __typename?: 'LaunchesPastResult', result?: Maybe, data?: Maybe>>, }; export type LaunchFind = { apoapsis_km?: Maybe, block?: Maybe, cap_serial?: Maybe, capsule_reuse?: Maybe, core_flight?: Maybe, core_reuse?: Maybe, core_serial?: Maybe, customer?: Maybe, eccentricity?: Maybe, end?: Maybe, epoch?: Maybe, fairings_recovered?: Maybe, fairings_recovery_attempt?: Maybe, fairings_reuse?: Maybe, fairings_reused?: Maybe, fairings_ship?: Maybe, gridfins?: Maybe, id?: Maybe, inclination_deg?: Maybe, land_success?: Maybe, landing_intent?: Maybe, landing_type?: Maybe, landing_vehicle?: Maybe, launch_date_local?: Maybe, launch_date_utc?: Maybe, launch_success?: Maybe, launch_year?: Maybe, legs?: Maybe, lifespan_years?: Maybe, longitude?: Maybe, manufacturer?: Maybe, mean_motion?: Maybe, mission_id?: Maybe, mission_name?: Maybe, nationality?: Maybe, norad_id?: Maybe, orbit?: Maybe, payload_id?: Maybe, payload_type?: Maybe, periapsis_km?: Maybe, period_min?: Maybe, raan?: Maybe, reference_system?: Maybe, regime?: Maybe, reused?: Maybe, rocket_id?: Maybe, rocket_name?: Maybe, rocket_type?: Maybe, second_stage_block?: Maybe, semi_major_axis_km?: Maybe, ship?: Maybe, side_core1_reuse?: Maybe, side_core2_reuse?: Maybe, site_id?: Maybe, site_name_long?: Maybe, site_name?: Maybe, start?: Maybe, tbd?: Maybe, tentative_max_precision?: Maybe, tentative?: Maybe, }; export type LaunchLinks = { __typename?: 'LaunchLinks', article_link?: Maybe, flickr_images?: Maybe>>, mission_patch_small?: Maybe, mission_patch?: Maybe, presskit?: Maybe, reddit_campaign?: Maybe, reddit_launch?: Maybe, reddit_media?: Maybe, reddit_recovery?: Maybe, video_link?: Maybe, wikipedia?: Maybe, }; export type Launchpad = { __typename?: 'Launchpad', attempted_launches?: Maybe, details?: Maybe, id?: Maybe, location?: Maybe, name?: Maybe, status?: Maybe, successful_launches?: Maybe, vehicles_launched?: Maybe>>, wikipedia?: Maybe, }; export type LaunchRocket = { __typename?: 'LaunchRocket', fairings?: Maybe, first_stage?: Maybe, rocket_name?: Maybe, rocket_type?: Maybe, rocket?: Maybe, second_stage?: Maybe, }; export type LaunchRocketFairings = { __typename?: 'LaunchRocketFairings', recovered?: Maybe, recovery_attempt?: Maybe, reused?: Maybe, ship?: Maybe, }; export type LaunchRocketFirstStage = { __typename?: 'LaunchRocketFirstStage', cores?: Maybe>>, }; export type LaunchRocketFirstStageCore = { __typename?: 'LaunchRocketFirstStageCore', block?: Maybe, core?: Maybe, flight?: Maybe, gridfins?: Maybe, land_success?: Maybe, landing_intent?: Maybe, landing_type?: Maybe, landing_vehicle?: Maybe, legs?: Maybe, reused?: Maybe, }; export type LaunchRocketSecondStage = { __typename?: 'LaunchRocketSecondStage', block?: Maybe, payloads?: Maybe>>, }; export type LaunchSite = { __typename?: 'LaunchSite', site_id?: Maybe, site_name_long?: Maybe, site_name?: Maybe, }; export type LaunchTelemetry = { __typename?: 'LaunchTelemetry', flight_club?: Maybe, }; export type Link = { __typename?: 'Link', article?: Maybe, reddit?: Maybe, wikipedia?: Maybe, }; export type Location = { __typename?: 'Location', latitude?: Maybe, longitude?: Maybe, name?: Maybe, region?: Maybe, }; export type Mass = { __typename?: 'Mass', kg?: Maybe, lb?: Maybe, }; export type Mission = { __typename?: 'Mission', description?: Maybe, id?: Maybe, manufacturers?: Maybe>>, name?: Maybe, twitter?: Maybe, website?: Maybe, wikipedia?: Maybe, payloads?: Maybe>>, }; export type MissionResult = { __typename?: 'MissionResult', result?: Maybe, data?: Maybe>>, }; export type MissionsFind = { id?: Maybe, manufacturer?: Maybe, name?: Maybe, payload_id?: Maybe, }; export type Payload = { __typename?: 'Payload', customers?: Maybe>>, id?: Maybe, manufacturer?: Maybe, nationality?: Maybe, norad_id?: Maybe>>, orbit_params?: Maybe, orbit?: Maybe, payload_mass_kg?: Maybe, payload_mass_lbs?: Maybe, payload_type?: Maybe, reused?: Maybe, }; export type PayloadOrbitParams = { __typename?: 'PayloadOrbitParams', apoapsis_km?: Maybe, arg_of_pericenter?: Maybe, eccentricity?: Maybe, epoch?: Maybe, inclination_deg?: Maybe, lifespan_years?: Maybe, longitude?: Maybe, mean_anomaly?: Maybe, mean_motion?: Maybe, periapsis_km?: Maybe, period_min?: Maybe, raan?: Maybe, reference_system?: Maybe, regime?: Maybe, semi_major_axis_km?: Maybe, }; export type PayloadsFind = { apoapsis_km?: Maybe, customer?: Maybe, eccentricity?: Maybe, epoch?: Maybe, inclination_deg?: Maybe, lifespan_years?: Maybe, longitude?: Maybe, manufacturer?: Maybe, mean_motion?: Maybe, nationality?: Maybe, norad_id?: Maybe, orbit?: Maybe, payload_id?: Maybe, payload_type?: Maybe, periapsis_km?: Maybe, period_min?: Maybe, raan?: Maybe, reference_system?: Maybe, regime?: Maybe, reused?: Maybe, semi_major_axis_km?: Maybe, }; export type Query = { __typename?: 'Query', capsules?: Maybe>>, capsulesPast?: Maybe>>, capsulesUpcoming?: Maybe>>, capsule?: Maybe, company?: Maybe, cores?: Maybe>>, coresPast?: Maybe>>, coresUpcoming?: Maybe>>, core?: Maybe, dragons?: Maybe>>, dragon?: Maybe, histories?: Maybe>>, historiesResult?: Maybe, history?: Maybe, landpads?: Maybe>>, landpad?: Maybe, launches?: Maybe>>, launchesPast?: Maybe>>, launchesPastResult?: Maybe, launchesUpcoming?: Maybe>>, launch?: Maybe, launchLatest?: Maybe, launchNext?: Maybe, launchpads?: Maybe>>, launchpad?: Maybe, missions?: Maybe>>, missionsResult?: Maybe, mission?: Maybe, payloads?: Maybe>>, payload?: Maybe, roadster?: Maybe, rockets?: Maybe>>, rocketsResult?: Maybe, rocket?: Maybe, ships?: Maybe>>, shipsResult?: Maybe, ship?: Maybe, }; export type QueryCapsulesArgs = { find?: Maybe, limit?: Maybe, offset?: Maybe, order?: Maybe, sort?: Maybe }; export type QueryCapsulesPastArgs = { find?: Maybe, limit?: Maybe, offset?: Maybe, order?: Maybe, sort?: Maybe }; export type QueryCapsulesUpcomingArgs = { find?: Maybe, limit?: Maybe, offset?: Maybe, order?: Maybe, sort?: Maybe }; export type QueryCapsuleArgs = { id: Scalars['ID'] }; export type QueryCoresArgs = { find?: Maybe, limit?: Maybe, offset?: Maybe, order?: Maybe, sort?: Maybe }; export type QueryCoresPastArgs = { find?: Maybe, limit?: Maybe, offset?: Maybe, order?: Maybe, sort?: Maybe }; export type QueryCoresUpcomingArgs = { find?: Maybe, limit?: Maybe, offset?: Maybe, order?: Maybe, sort?: Maybe }; export type QueryCoreArgs = { id: Scalars['ID'] }; export type QueryDragonsArgs = { limit?: Maybe, offset?: Maybe }; export type QueryDragonArgs = { id: Scalars['ID'] }; export type QueryHistoriesArgs = { find?: Maybe, limit?: Maybe, offset?: Maybe, order?: Maybe, sort?: Maybe }; export type QueryHistoriesResultArgs = { find?: Maybe, limit?: Maybe, offset?: Maybe, order?: Maybe, sort?: Maybe }; export type QueryHistoryArgs = { id: Scalars['ID'] }; export type QueryLandpadsArgs = { limit?: Maybe, offset?: Maybe }; export type QueryLandpadArgs = { id: Scalars['ID'] }; export type QueryLaunchesArgs = { find?: Maybe, limit?: Maybe, offset?: Maybe, order?: Maybe, sort?: Maybe }; export type QueryLaunchesPastArgs = { find?: Maybe, limit?: Maybe, offset?: Maybe, order?: Maybe, sort?: Maybe }; export type QueryLaunchesPastResultArgs = { find?: Maybe, limit?: Maybe, offset?: Maybe, order?: Maybe, sort?: Maybe }; export type QueryLaunchesUpcomingArgs = { find?: Maybe, limit?: Maybe, offset?: Maybe, order?: Maybe, sort?: Maybe }; export type QueryLaunchArgs = { id: Scalars['ID'] }; export type QueryLaunchLatestArgs = { offset?: Maybe }; export type QueryLaunchNextArgs = { offset?: Maybe }; export type QueryLaunchpadsArgs = { limit?: Maybe, offset?: Maybe }; export type QueryLaunchpadArgs = { id: Scalars['ID'] }; export type QueryMissionsArgs = { find?: Maybe, limit?: Maybe, offset?: Maybe }; export type QueryMissionsResultArgs = { find?: Maybe, limit?: Maybe, offset?: Maybe }; export type QueryMissionArgs = { id: Scalars['ID'] }; export type QueryPayloadsArgs = { find?: Maybe, limit?: Maybe, offset?: Maybe, order?: Maybe, sort?: Maybe }; export type QueryPayloadArgs = { id: Scalars['ID'] }; export type QueryRocketsArgs = { limit?: Maybe, offset?: Maybe }; export type QueryRocketsResultArgs = { limit?: Maybe, offset?: Maybe }; export type QueryRocketArgs = { id: Scalars['ID'] }; export type QueryShipsArgs = { find?: Maybe, limit?: Maybe, offset?: Maybe, order?: Maybe, sort?: Maybe }; export type QueryShipsResultArgs = { find?: Maybe, limit?: Maybe, offset?: Maybe, order?: Maybe, sort?: Maybe }; export type QueryShipArgs = { id: Scalars['ID'] }; export type Result = { __typename?: 'Result', totalCount?: Maybe, }; export type Roadster = { __typename?: 'Roadster', apoapsis_au?: Maybe, details?: Maybe, earth_distance_km?: Maybe, earth_distance_mi?: Maybe, eccentricity?: Maybe, epoch_jd?: Maybe, inclination?: Maybe, launch_date_unix?: Maybe, launch_date_utc?: Maybe, launch_mass_kg?: Maybe, launch_mass_lbs?: Maybe, longitude?: Maybe, mars_distance_km?: Maybe, mars_distance_mi?: Maybe, name?: Maybe, norad_id?: Maybe, orbit_type?: Maybe, periapsis_arg?: Maybe, periapsis_au?: Maybe, period_days?: Maybe, semi_major_axis_au?: Maybe, speed_kph?: Maybe, speed_mph?: Maybe, wikipedia?: Maybe, }; export type Rocket = { __typename?: 'Rocket', active?: Maybe, boosters?: Maybe, company?: Maybe, cost_per_launch?: Maybe, country?: Maybe, description?: Maybe, diameter?: Maybe, engines?: Maybe, first_flight?: Maybe, first_stage?: Maybe, height?: Maybe, id?: Maybe, landing_legs?: Maybe, mass?: Maybe, name?: Maybe, payload_weights?: Maybe>>, second_stage?: Maybe, stages?: Maybe, success_rate_pct?: Maybe, type?: Maybe, wikipedia?: Maybe, }; export type RocketEngines = { __typename?: 'RocketEngines', number?: Maybe, type?: Maybe, version?: Maybe, layout?: Maybe, engine_loss_max?: Maybe, propellant_1?: Maybe, propellant_2?: Maybe, thrust_sea_level?: Maybe, thrust_vacuum?: Maybe, thrust_to_weight?: Maybe, }; export type RocketFirstStage = { __typename?: 'RocketFirstStage', burn_time_sec?: Maybe, engines?: Maybe, fuel_amount_tons?: Maybe, reusable?: Maybe, thrust_sea_level?: Maybe, thrust_vacuum?: Maybe, }; export type RocketLandingLegs = { __typename?: 'RocketLandingLegs', number?: Maybe, material?: Maybe, }; export type RocketPayloadWeight = { __typename?: 'RocketPayloadWeight', id?: Maybe, kg?: Maybe, lb?: Maybe, name?: Maybe, }; export type RocketSecondStage = { __typename?: 'RocketSecondStage', burn_time_sec?: Maybe, engines?: Maybe, fuel_amount_tons?: Maybe, payloads?: Maybe, thrust?: Maybe, }; export type RocketSecondStagePayloadCompositeFairing = { __typename?: 'RocketSecondStagePayloadCompositeFairing', height?: Maybe, diameter?: Maybe, }; export type RocketSecondStagePayloads = { __typename?: 'RocketSecondStagePayloads', option_1?: Maybe, composite_fairing?: Maybe, }; export type RocketsResult = { __typename?: 'RocketsResult', result?: Maybe, data?: Maybe>>, }; export type Ship = { __typename?: 'Ship', abs?: Maybe, active?: Maybe, attempted_landings?: Maybe, class?: Maybe, course_deg?: Maybe, home_port?: Maybe, id?: Maybe, image?: Maybe, imo?: Maybe, missions?: Maybe>>, mmsi?: Maybe, model?: Maybe, name?: Maybe, position?: Maybe, roles?: Maybe>>, speed_kn?: Maybe, status?: Maybe, successful_landings?: Maybe, type?: Maybe, url?: Maybe, weight_kg?: Maybe, weight_lbs?: Maybe, year_built?: Maybe, }; export type ShipLocation = { __typename?: 'ShipLocation', latitude?: Maybe, longitude?: Maybe, }; export type ShipMission = { __typename?: 'ShipMission', flight?: Maybe, name?: Maybe, }; export type ShipsFind = { id?: Maybe, name?: Maybe, model?: Maybe, type?: Maybe, role?: Maybe, active?: Maybe, imo?: Maybe, mmsi?: Maybe, abs?: Maybe, class?: Maybe, weight_lbs?: Maybe, weight_kg?: Maybe, year_built?: Maybe, home_port?: Maybe, status?: Maybe, speed_kn?: Maybe, course_deg?: Maybe, latitude?: Maybe, longitude?: Maybe, successful_landings?: Maybe, attempted_landings?: Maybe, mission?: Maybe, }; export type ShipsResult = { __typename?: 'ShipsResult', result?: Maybe, data?: Maybe>>, }; export type Volume = { __typename?: 'Volume', cubic_feet?: Maybe, cubic_meters?: Maybe, }; export type LaunchDetailsQueryVariables = { id: Scalars['ID'] }; export type LaunchDetailsQuery = ( { __typename?: 'Query' } & { launch: Maybe<( { __typename?: 'Launch' } & Pick & { links: Maybe<( { __typename?: 'LaunchLinks' } & Pick )> } )> } ); export type PastLaunchesListQueryVariables = { limit: Scalars['Int'] }; export type PastLaunchesListQuery = ( { __typename?: 'Query' } & { launchesPast: Maybe & { links: Maybe<( { __typename?: 'LaunchLinks' } & Pick )>, rocket: Maybe<( { __typename?: 'LaunchRocket' } & Pick )> } )>>> } ); export const LaunchDetailsDocument = gql` query launchDetails($id: ID!) { launch(id: $id) { id mission_name details links { flickr_images mission_patch } } } `; @Injectable({ providedIn: 'root' }) export class LaunchDetailsGQL extends Apollo.Query { document = LaunchDetailsDocument; } export const PastLaunchesListDocument = gql` query pastLaunchesList($limit: Int!) { launchesPast(limit: $limit) { id mission_name links { flickr_images mission_patch_small } rocket { rocket_name } launch_date_utc } } `; @Injectable({ providedIn: 'root' }) export class PastLaunchesListGQL extends Apollo.Query { document = PastLaunchesListDocument; } ================================================ FILE: src/assets/.gitkeep ================================================ ================================================ FILE: src/environments/environment.prod.ts ================================================ export const environment = { production: true }; ================================================ FILE: src/environments/environment.ts ================================================ // This file can be replaced during build by using the `fileReplacements` array. // `ng build --prod` replaces `environment.ts` with `environment.prod.ts`. // The list of file replacements can be found in `angular.json`. export const environment = { production: false }; /* * For easier debugging in development mode, you can import the following file * to ignore zone related error stack frames such as `zone.run`, `zoneDelegate.invokeTask`. * * This import should be commented out in production mode because it will have a negative impact * on performance if an error is thrown. */ // import 'zone.js/dist/zone-error'; // Included with Angular CLI. ================================================ FILE: src/index.html ================================================ AngularSpacexGraphqlCodegen ================================================ FILE: src/main.ts ================================================ import 'hammerjs'; import { enableProdMode } from '@angular/core'; import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { AppModule } from './app/app.module'; import { environment } from './environments/environment'; if (environment.production) { enableProdMode(); } platformBrowserDynamic().bootstrapModule(AppModule) .catch(err => console.error(err)); ================================================ FILE: src/polyfills.ts ================================================ /** * This file includes polyfills needed by Angular and is loaded before the app. * You can add your own extra polyfills to this file. * * This file is divided into 2 sections: * 1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers. * 2. Application imports. Files imported after ZoneJS that should be loaded before your main * file. * * The current setup is for so-called "evergreen" browsers; the last versions of browsers that * automatically update themselves. This includes Safari >= 10, Chrome >= 55 (including Opera), * Edge >= 13 on the desktop, and iOS 10 and Chrome on mobile. * * Learn more in https://angular.io/guide/browser-support */ /*************************************************************************************************** * BROWSER POLYFILLS */ /** IE10 and IE11 requires the following for NgClass support on SVG elements */ // import 'classlist.js'; // Run `npm install --save classlist.js`. /** * Web Animations `@angular/platform-browser/animations` * Only required if AnimationBuilder is used within the application and using IE/Edge or Safari. * Standard animation support in Angular DOES NOT require any polyfills (as of Angular 6.0). */ // import 'web-animations-js'; // Run `npm install --save web-animations-js`. /** * By default, zone.js will patch all possible macroTask and DomEvents * user can disable parts of macroTask/DomEvents patch by setting following flags * because those flags need to be set before `zone.js` being loaded, and webpack * will put import in the top of bundle, so user need to create a separate file * in this directory (for example: zone-flags.ts), and put the following flags * into that file, and then add the following code before importing zone.js. * import './zone-flags.ts'; * * The flags allowed in zone-flags.ts are listed here. * * The following flags will work for all browsers. * * (window as any).__Zone_disable_requestAnimationFrame = true; // disable patch requestAnimationFrame * (window as any).__Zone_disable_on_property = true; // disable patch onProperty such as onclick * (window as any).__zone_symbol__UNPATCHED_EVENTS = ['scroll', 'mousemove']; // disable patch specified eventNames * * in IE/Edge developer tools, the addEventListener will also be wrapped by zone.js * with the following flag, it will bypass `zone.js` patch for IE/Edge * * (window as any).__Zone_enable_cross_context_check = true; * */ /*************************************************************************************************** * Zone JS is required by default for Angular itself. */ import 'zone.js/dist/zone'; // Included with Angular CLI. /*************************************************************************************************** * APPLICATION IMPORTS */ ================================================ FILE: src/styles.css ================================================ /* You can add global styles to this file, and also import other style files */ html, body { height: 100%; } body { margin: 0; font-family: Roboto, "Helvetica Neue", sans-serif; } ================================================ FILE: src/test.ts ================================================ // This file is required by karma.conf.js and loads recursively all the .spec and framework files import 'zone.js/dist/zone-testing'; import { getTestBed } from '@angular/core/testing'; import { BrowserDynamicTestingModule, platformBrowserDynamicTesting } from '@angular/platform-browser-dynamic/testing'; declare const require: any; // First, initialize the Angular testing environment. getTestBed().initTestEnvironment( BrowserDynamicTestingModule, platformBrowserDynamicTesting() ); // Then we find all the tests. const context = require.context('./', true, /\.spec\.ts$/); // And load the modules. context.keys().map(context); ================================================ FILE: tsconfig.app.json ================================================ { "extends": "./tsconfig.json", "compilerOptions": { "outDir": "./out-tsc/app", "types": [] }, "files": [ "src/main.ts", "src/polyfills.ts" ], "include": [ "src/**/*.ts" ], "exclude": [ "src/test.ts", "src/**/*.spec.ts" ] } ================================================ FILE: tsconfig.json ================================================ { "compileOnSave": false, "compilerOptions": { "baseUrl": "./", "outDir": "./dist/out-tsc", "sourceMap": true, "declaration": false, "downlevelIteration": true, "experimentalDecorators": true, "module": "esnext", "moduleResolution": "node", "importHelpers": true, "target": "es2015", "typeRoots": [ "node_modules/@types" ], "lib": [ "es2018", "dom", "esnext.asynciterable" ] }, "angularCompilerOptions": { "fullTemplateTypeCheck": true, "strictInjectionParameters": true } } ================================================ FILE: tsconfig.spec.json ================================================ { "extends": "./tsconfig.json", "compilerOptions": { "outDir": "./out-tsc/spec", "types": [ "jasmine", "node" ] }, "files": [ "src/test.ts", "src/polyfills.ts" ], "include": [ "src/**/*.spec.ts", "src/**/*.d.ts" ] } ================================================ FILE: tslint.json ================================================ { "extends": "tslint:recommended", "rules": { "array-type": false, "arrow-parens": false, "deprecation": { "severity": "warning" }, "component-class-suffix": true, "contextual-lifecycle": true, "directive-class-suffix": true, "directive-selector": [ true, "attribute", "app", "camelCase" ], "component-selector": [ true, "element", "app", "kebab-case" ], "import-blacklist": [ true, "rxjs/Rx" ], "interface-name": false, "max-classes-per-file": false, "max-line-length": [ true, 140 ], "member-access": false, "member-ordering": [ true, { "order": [ "static-field", "instance-field", "static-method", "instance-method" ] } ], "no-consecutive-blank-lines": false, "no-console": [ true, "debug", "info", "time", "timeEnd", "trace" ], "no-empty": false, "no-inferrable-types": [ true, "ignore-params" ], "no-non-null-assertion": true, "no-redundant-jsdoc": true, "no-switch-case-fall-through": true, "no-use-before-declare": true, "no-var-requires": false, "object-literal-key-quotes": [ true, "as-needed" ], "object-literal-sort-keys": false, "ordered-imports": false, "quotemark": [ true, "single" ], "trailing-comma": false, "no-conflicting-lifecycle": true, "no-host-metadata-property": true, "no-input-rename": true, "no-inputs-metadata-property": true, "no-output-native": true, "no-output-on-prefix": true, "no-output-rename": true, "no-outputs-metadata-property": true, "template-banana-in-box": true, "template-no-negated-async": true, "use-lifecycle-interface": true, "use-pipe-transform-interface": true }, "rulesDirectory": [ "codelyzer" ] }