add: stand configs
This commit is contained in:
@@ -0,0 +1,3 @@
|
||||
# Tests
|
||||
|
||||
Please place your tests in this folder.
|
||||
@@ -0,0 +1,31 @@
|
||||
import {Client} from '@loopback/testlab';
|
||||
import {Loopback4ExampleGithubApplication} from '../..';
|
||||
import {setupApplication} from './test-helper';
|
||||
|
||||
describe('HomePage', () => {
|
||||
let app: Loopback4ExampleGithubApplication;
|
||||
let client: Client;
|
||||
|
||||
before('setupApplication', async () => {
|
||||
({app, client} = await setupApplication());
|
||||
});
|
||||
|
||||
after(async () => {
|
||||
await app.stop();
|
||||
});
|
||||
|
||||
it('exposes a default home page', async () => {
|
||||
await client
|
||||
.get('/')
|
||||
.expect(200)
|
||||
.expect('Content-Type', /text\/html/);
|
||||
});
|
||||
|
||||
it('exposes self-hosted explorer', async () => {
|
||||
await client
|
||||
.get('/explorer/')
|
||||
.expect(200)
|
||||
.expect('Content-Type', /text\/html/)
|
||||
.expect(/<title>LoopBack API Explorer/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,21 @@
|
||||
import {Client, expect} from '@loopback/testlab';
|
||||
import {Loopback4ExampleGithubApplication} from '../..';
|
||||
import {setupApplication} from './test-helper';
|
||||
|
||||
describe('PingController', () => {
|
||||
let app: Loopback4ExampleGithubApplication;
|
||||
let client: Client;
|
||||
|
||||
before('setupApplication', async () => {
|
||||
({app, client} = await setupApplication());
|
||||
});
|
||||
|
||||
after(async () => {
|
||||
await app.stop();
|
||||
});
|
||||
|
||||
it('invokes GET /ping', async () => {
|
||||
const res = await client.get('/ping?msg=world').expect(200);
|
||||
expect(res.body).to.containEql({greeting: 'Hello from LoopBack'});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,32 @@
|
||||
import {Loopback4ExampleGithubApplication} from '../..';
|
||||
import {
|
||||
createRestAppClient,
|
||||
givenHttpServerConfig,
|
||||
Client,
|
||||
} from '@loopback/testlab';
|
||||
|
||||
export async function setupApplication(): Promise<AppWithClient> {
|
||||
const restConfig = givenHttpServerConfig({
|
||||
// Customize the server configuration here.
|
||||
// Empty values (undefined, '') will be ignored by the helper.
|
||||
//
|
||||
// host: process.env.HOST,
|
||||
// port: +process.env.PORT,
|
||||
});
|
||||
|
||||
const app = new Loopback4ExampleGithubApplication({
|
||||
rest: restConfig,
|
||||
});
|
||||
|
||||
await app.boot();
|
||||
await app.start();
|
||||
|
||||
const client = createRestAppClient(app);
|
||||
|
||||
return {app, client};
|
||||
}
|
||||
|
||||
export interface AppWithClient {
|
||||
app: Loopback4ExampleGithubApplication;
|
||||
client: Client;
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import {BootMixin} from '@loopback/boot';
|
||||
import {ApplicationConfig} from '@loopback/core';
|
||||
import {
|
||||
RestExplorerBindings,
|
||||
RestExplorerComponent,
|
||||
} from '@loopback/rest-explorer';
|
||||
import {RepositoryMixin} from '@loopback/repository';
|
||||
import {RestApplication} from '@loopback/rest';
|
||||
import {ServiceMixin} from '@loopback/service-proxy';
|
||||
import path from 'path';
|
||||
import {MySequence} from './sequence';
|
||||
|
||||
export {ApplicationConfig};
|
||||
|
||||
export class Loopback4ExampleGithubApplication extends BootMixin(
|
||||
ServiceMixin(RepositoryMixin(RestApplication)),
|
||||
) {
|
||||
constructor(options: ApplicationConfig = {}) {
|
||||
super(options);
|
||||
|
||||
// Подключаем кастомную sequence для обработки запросов.
|
||||
this.sequence(MySequence);
|
||||
|
||||
// Главная страница из папки public.
|
||||
this.static('/', path.join(__dirname, '../public'));
|
||||
|
||||
// Включаем REST Explorer.
|
||||
this.configure(RestExplorerBindings.COMPONENT).to({
|
||||
path: '/explorer',
|
||||
});
|
||||
this.component(RestExplorerComponent);
|
||||
|
||||
this.projectRoot = __dirname;
|
||||
// Настройки автозагрузки контроллеров.
|
||||
this.bootOptions = {
|
||||
controllers: {
|
||||
// Ищем контроллеры в папке controllers.
|
||||
dirs: ['controllers'],
|
||||
extensions: ['.controller.js'],
|
||||
nested: true,
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
# Controllers
|
||||
|
||||
This directory contains source files for the controllers exported by this app.
|
||||
|
||||
To add a new empty controller, type in `lb4 controller [<name>]` from the
|
||||
command-line of your application's root directory.
|
||||
|
||||
For more information, please visit
|
||||
[Controller generator](http://loopback.io/doc/en/lb4/Controller-generator.html).
|
||||
@@ -0,0 +1,134 @@
|
||||
// Uncomment these imports to begin using these cool features!
|
||||
|
||||
import {inject} from '@loopback/context';
|
||||
import {get, getModelSchemaRef, param} from '@loopback/openapi-v3';
|
||||
import {QueryResult, ResultIssueInfo} from '../models';
|
||||
import {GhQueryService, IssueInfo, QueryResponse} from '../services';
|
||||
|
||||
// import {inject} from '@loopback/core';
|
||||
|
||||
|
||||
export class GhQueryController {
|
||||
// inject the GhQueryService service proxy
|
||||
constructor(@inject('services.GhQueryService') protected queryService:GhQueryService) {}
|
||||
|
||||
// create the API that get the issues by providing:
|
||||
// repo: <GitHub org>/<GitHub repo>. For example, `strongloop/loopback-next`
|
||||
// label: If it has special characters, you need to escape it.
|
||||
// For example, if the label is "help wanted", it will be "help+wanted".
|
||||
@get('/issues/repo/{repo}/label/{label}', {
|
||||
responses: {
|
||||
'200': {
|
||||
description: 'Array of GitHub issues info',
|
||||
content: {
|
||||
'application/json': {
|
||||
schema: getModelSchemaRef(QueryResult)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
async getIssuesByLabel(
|
||||
@param.path.string('repo') repo: string,
|
||||
@param.path.string('label') label:string): Promise<QueryResult> {
|
||||
let result:QueryResponse = await this.queryService.getIssuesByLabel(repo, label);
|
||||
let queryResult = new QueryResult();
|
||||
queryResult.items = [];
|
||||
queryResult.total_count = result.body.total_count;
|
||||
result.body.items.forEach(issue => {
|
||||
this.addToResult(issue, queryResult);
|
||||
});
|
||||
|
||||
// check if there is next page of the results
|
||||
const nextLink = this.getNextLink(result.headers.link);
|
||||
if (nextLink == null) return queryResult;
|
||||
await this.getIssueByURL(nextLink, this.queryService, queryResult);
|
||||
return queryResult;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get issues from URL
|
||||
* @param nextLinkURL
|
||||
* @param queryService
|
||||
* @param queryResult
|
||||
* @returns
|
||||
*/
|
||||
async getIssueByURL(nextLinkURL: string, queryService: GhQueryService, queryResult:QueryResult) {
|
||||
let result = await queryService.getIssuesByURL(nextLinkURL);
|
||||
result.body.items.forEach(issue => {
|
||||
this.addToResult(issue, queryResult);
|
||||
});
|
||||
|
||||
const nextLink2 = this.getNextLink(result.headers.link);
|
||||
if (nextLink2 == null) return;
|
||||
await this.getIssueByURL(nextLink2, queryService, queryResult);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the URL for the "next" page.
|
||||
* The Link header is in the format of:
|
||||
* Link: <https://api.github.com/search/code?q=addClass+user%3Amozilla&page=2>; rel="next",
|
||||
<https://api.github.com/search/code?q=addClass+user%3Amozilla&page=34>; rel="last"
|
||||
* @param link
|
||||
* @returns
|
||||
*/
|
||||
getNextLink(link: string): string|null {
|
||||
if (link == undefined) return null;
|
||||
|
||||
let tokens: string[] = link.split(',');
|
||||
let url: string|null = null;
|
||||
|
||||
tokens.forEach(token => {
|
||||
if (token.indexOf('rel="next"')!=-1) {
|
||||
url = token.substring(token.indexOf('<')+1, token.indexOf(';')-1);
|
||||
}
|
||||
});
|
||||
|
||||
return url;
|
||||
}
|
||||
/**
|
||||
* Add the issue to the QueryResult object
|
||||
* @param issue
|
||||
* @param queryResult
|
||||
*/
|
||||
addToResult(issue: IssueInfo, queryResult: QueryResult) {
|
||||
let issueInfo:ResultIssueInfo = new ResultIssueInfo();
|
||||
issueInfo.html_url = issue.html_url;
|
||||
issueInfo.title = issue.title;
|
||||
issueInfo.state = issue.state;
|
||||
issueInfo.age = this.getIssueAge(issue.created_at);
|
||||
queryResult.items?.push(issueInfo);
|
||||
}
|
||||
/**
|
||||
* Calculate the age of the issue
|
||||
* i.e. take today's date and find the number of days difference from
|
||||
* the issue creation date
|
||||
* @param created_at
|
||||
* @returns
|
||||
*/
|
||||
getIssueAge(created_at: string): number {
|
||||
let todayDate: Date = new Date();
|
||||
let createDate: Date = new Date(created_at);
|
||||
let differenceInTime = todayDate.getTime() - createDate.getTime();
|
||||
|
||||
//get the difference in day
|
||||
return Math.floor(differenceInTime / (1000 * 3600 * 24));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
// /**
|
||||
// * QueryResult
|
||||
// */
|
||||
// class QueryResult {
|
||||
// total_count: number;
|
||||
// items: ResultIssueInfo[];
|
||||
// }
|
||||
|
||||
// class ResultIssueInfo {
|
||||
// title: string;
|
||||
// html_url: string;
|
||||
// state: string;
|
||||
// age: number;
|
||||
// }
|
||||
@@ -0,0 +1,2 @@
|
||||
export * from './ping.controller';
|
||||
export * from './gh-query.controller';
|
||||
@@ -0,0 +1,55 @@
|
||||
import {inject} from '@loopback/core';
|
||||
import {
|
||||
Request,
|
||||
RestBindings,
|
||||
get,
|
||||
response,
|
||||
ResponseObject,
|
||||
} from '@loopback/rest';
|
||||
|
||||
/**
|
||||
* OpenAPI response for ping()
|
||||
*/
|
||||
const PING_RESPONSE: ResponseObject = {
|
||||
description: 'Ping Response',
|
||||
content: {
|
||||
'application/json': {
|
||||
schema: {
|
||||
type: 'object',
|
||||
title: 'PingResponse',
|
||||
properties: {
|
||||
greeting: {type: 'string'},
|
||||
date: {type: 'string'},
|
||||
url: {type: 'string'},
|
||||
headers: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
'Content-Type': {type: 'string'},
|
||||
},
|
||||
additionalProperties: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* A simple controller to bounce back http requests
|
||||
*/
|
||||
export class PingController {
|
||||
constructor(@inject(RestBindings.Http.REQUEST) private req: Request) {}
|
||||
|
||||
// Map to `GET /ping`
|
||||
@get('/ping')
|
||||
@response(200, PING_RESPONSE)
|
||||
ping(): object {
|
||||
// Reply with a greeting, the current time, the url, and request headers
|
||||
return {
|
||||
greeting: 'Hello from LoopBack',
|
||||
date: new Date(),
|
||||
url: this.req.url,
|
||||
headers: Object.assign({}, this.req.headers),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
# Datasources
|
||||
|
||||
This directory contains config for datasources used by this app.
|
||||
@@ -0,0 +1,66 @@
|
||||
import {inject, lifeCycleObserver, LifeCycleObserver} from '@loopback/core';
|
||||
import {juggler} from '@loopback/repository';
|
||||
|
||||
const config = {
|
||||
name: 'githubds',
|
||||
connector: 'rest',
|
||||
baseURL: 'https://api.github.ibm.com',
|
||||
crud: false,
|
||||
options: {
|
||||
headers: {
|
||||
accept: 'application/json',
|
||||
Authorization: process.env.TOKEN,
|
||||
'User-Agent': 'loopback4-example-github',
|
||||
'X-RateLimit-Limit': 5000,
|
||||
'content-type': 'application/json'
|
||||
}
|
||||
},
|
||||
operations: [
|
||||
{
|
||||
template: {
|
||||
method: 'GET',
|
||||
fullResponse: true,
|
||||
url: 'https://api.github.com/search/issues?q=repo:{repo}+label:"{label}"'
|
||||
},
|
||||
functions: {
|
||||
getIssuesByLabel: ['repo','label']
|
||||
}
|
||||
}, {
|
||||
template: {
|
||||
method: 'GET',
|
||||
fullResponse: true,
|
||||
url: '{url}'
|
||||
},
|
||||
functions: {
|
||||
getIssuesByURL: ['url']
|
||||
}
|
||||
}, {
|
||||
template: {
|
||||
method: 'GET',
|
||||
fullResponse: true,
|
||||
url: 'https://api.github.com/search/issues?q=repo:{repo}+{querystring}'
|
||||
},
|
||||
functions: {
|
||||
getIssuesWithQueryString: ['repo','querystring']
|
||||
}
|
||||
}
|
||||
]
|
||||
};
|
||||
|
||||
// Observe application's life cycle to disconnect the datasource when
|
||||
// application is stopped. This allows the application to be shut down
|
||||
// gracefully. The `stop()` method is inherited from `juggler.DataSource`.
|
||||
// Learn more at https://loopback.io/doc/en/lb4/Life-cycle.html
|
||||
@lifeCycleObserver('datasource')
|
||||
export class GithubdsDataSource extends juggler.DataSource
|
||||
implements LifeCycleObserver {
|
||||
static dataSourceName = 'githubds';
|
||||
static readonly defaultConfig = config;
|
||||
|
||||
constructor(
|
||||
@inject('datasources.config.githubds', {optional: true})
|
||||
dsConfig: object = config,
|
||||
) {
|
||||
super(dsConfig);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export * from './githubds.datasource';
|
||||
@@ -0,0 +1,40 @@
|
||||
import {ApplicationConfig, Loopback4ExampleGithubApplication} from './application';
|
||||
|
||||
export * from './application';
|
||||
|
||||
export async function main(options: ApplicationConfig = {}) {
|
||||
// Создаем и запускаем LoopBack приложение.
|
||||
const app = new Loopback4ExampleGithubApplication(options);
|
||||
await app.boot();
|
||||
await app.start();
|
||||
|
||||
const url = app.restServer.url;
|
||||
console.log(`Server is running at ${url}`);
|
||||
console.log(`Try ${url}/ping`);
|
||||
|
||||
return app;
|
||||
}
|
||||
|
||||
if (require.main === module) {
|
||||
// Локальный запуск с базовой конфигурацией REST.
|
||||
const config = {
|
||||
rest: {
|
||||
port: +(process.env.PORT ?? 3000),
|
||||
host: process.env.HOST,
|
||||
// The `gracePeriodForClose` provides a graceful close for http/https
|
||||
// servers with keep-alive clients. The default value is `Infinity`
|
||||
// (don't force-close). If you want to immediately destroy all sockets
|
||||
// upon stop, set its value to `0`.
|
||||
// See https://www.npmjs.com/package/stoppable
|
||||
gracePeriodForClose: 5000, // 5 seconds
|
||||
openApiSpec: {
|
||||
// useful when used with OpenAPI-to-GraphQL to locate your application
|
||||
setServersFromRequest: true,
|
||||
},
|
||||
},
|
||||
};
|
||||
main(config).catch(err => {
|
||||
console.error('Cannot start the application.', err);
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import {Loopback4ExampleGithubApplication} from './application';
|
||||
|
||||
export async function migrate(args: string[]) {
|
||||
const existingSchema = args.includes('--rebuild') ? 'drop' : 'alter';
|
||||
console.log('Migrating schemas (%s existing schema)', existingSchema);
|
||||
|
||||
const app = new Loopback4ExampleGithubApplication();
|
||||
await app.boot();
|
||||
await app.migrateSchema({existingSchema});
|
||||
|
||||
// Connectors usually keep a pool of opened connections,
|
||||
// this keeps the process running even after all work is done.
|
||||
// We need to exit explicitly.
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
migrate(process.argv).catch(err => {
|
||||
console.error('Cannot migrate database schema', err);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -0,0 +1,3 @@
|
||||
# Models
|
||||
|
||||
This directory contains code for models provided by this app.
|
||||
@@ -0,0 +1,2 @@
|
||||
export * from './query-result.model';
|
||||
export * from './result-issue-info.model';
|
||||
@@ -0,0 +1,24 @@
|
||||
import {Model, model, property} from '@loopback/repository';
|
||||
import {ResultIssueInfo} from './result-issue-info.model';
|
||||
|
||||
@model()
|
||||
export class QueryResult extends Model {
|
||||
@property({
|
||||
type: 'number',
|
||||
})
|
||||
total_count?: number;
|
||||
|
||||
@property.array(ResultIssueInfo)
|
||||
items?: ResultIssueInfo[];
|
||||
|
||||
|
||||
constructor(data?: Partial<QueryResult>) {
|
||||
super(data);
|
||||
}
|
||||
}
|
||||
|
||||
export interface QueryResultRelations {
|
||||
// describe navigational properties here
|
||||
}
|
||||
|
||||
export type QueryResultWithRelations = QueryResult & QueryResultRelations;
|
||||
@@ -0,0 +1,35 @@
|
||||
import {Model, model, property} from '@loopback/repository';
|
||||
|
||||
@model()
|
||||
export class ResultIssueInfo extends Model {
|
||||
@property({
|
||||
type: 'string',
|
||||
})
|
||||
title?: string;
|
||||
|
||||
@property({
|
||||
type: 'string',
|
||||
})
|
||||
html_url?: string;
|
||||
|
||||
@property({
|
||||
type: 'string',
|
||||
})
|
||||
state?: string;
|
||||
|
||||
@property({
|
||||
type: 'number',
|
||||
})
|
||||
age?: number;
|
||||
|
||||
|
||||
constructor(data?: Partial<ResultIssueInfo>) {
|
||||
super(data);
|
||||
}
|
||||
}
|
||||
|
||||
export interface ResultIssueInfoRelations {
|
||||
// describe navigational properties here
|
||||
}
|
||||
|
||||
export type ResultIssueInfoWithRelations = ResultIssueInfo & ResultIssueInfoRelations;
|
||||
@@ -0,0 +1,23 @@
|
||||
import {ApplicationConfig} from '@loopback/core';
|
||||
import {Loopback4ExampleGithubApplication} from './application';
|
||||
|
||||
/**
|
||||
* Export the OpenAPI spec from the application
|
||||
*/
|
||||
async function exportOpenApiSpec(): Promise<void> {
|
||||
const config: ApplicationConfig = {
|
||||
rest: {
|
||||
port: +(process.env.PORT ?? 3000),
|
||||
host: process.env.HOST ?? 'localhost',
|
||||
},
|
||||
};
|
||||
const outFile = process.argv[2] ?? '';
|
||||
const app = new Loopback4ExampleGithubApplication(config);
|
||||
await app.boot();
|
||||
await app.exportOpenApiSpec(outFile);
|
||||
}
|
||||
|
||||
exportOpenApiSpec().catch(err => {
|
||||
console.error('Fail to export OpenAPI spec from the application.', err);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -0,0 +1,3 @@
|
||||
# Repositories
|
||||
|
||||
This directory contains code for repositories provided by this app.
|
||||
@@ -0,0 +1,4 @@
|
||||
import {MiddlewareSequence} from '@loopback/rest';
|
||||
|
||||
// Стандартная sequence без кастомной логики.
|
||||
export class MySequence extends MiddlewareSequence {}
|
||||
@@ -0,0 +1,45 @@
|
||||
import {inject, Provider} from '@loopback/core';
|
||||
import {getService} from '@loopback/service-proxy';
|
||||
import {GithubdsDataSource} from '../datasources';
|
||||
|
||||
export interface GhQueryService {
|
||||
// this is where you define the Node.js methods that will be
|
||||
// mapped to REST/SOAP/gRPC operations as stated in the datasource
|
||||
// json file.
|
||||
|
||||
// Add the three methods here.
|
||||
// Make sure the function names and the parameter names matches
|
||||
// the ones you defined in the datasource
|
||||
getIssuesByLabel(repo: string, label: string): Promise<QueryResponse>;
|
||||
getIssuesByURL(url: string): Promise<QueryResponse>;
|
||||
getIssuesWithQueryString(repo:string, querystring: string): Promise<QueryResponse>;
|
||||
}
|
||||
|
||||
export interface QueryResponse {
|
||||
headers: any;
|
||||
body: QueryResponseBody;
|
||||
}
|
||||
export interface QueryResponseBody {
|
||||
total_count: number;
|
||||
items: IssueInfo[];
|
||||
}
|
||||
|
||||
export class IssueInfo {
|
||||
title: string;
|
||||
html_url: string;
|
||||
state: string;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
|
||||
export class GhQueryServiceProvider implements Provider<GhQueryService> {
|
||||
constructor(
|
||||
// githubds must match the name property in the datasource json file
|
||||
@inject('datasources.githubds')
|
||||
protected dataSource: GithubdsDataSource = new GithubdsDataSource(),
|
||||
) {}
|
||||
|
||||
value(): Promise<GhQueryService> {
|
||||
return getService(this.dataSource);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export * from './gh-query-service.service';
|
||||
Reference in New Issue
Block a user