add: stand configs
This commit is contained in:
@@ -0,0 +1,28 @@
|
||||
/*
|
||||
resource "nubes_flask" "app4" {
|
||||
resource_name = "flask_0"
|
||||
resource_realm = nubes_postgres.db2.resource_realm
|
||||
domain = "flask"
|
||||
git_path = "https://gitea-naeel.giteak8s.services.ngcloud.ru/naeel/testflask.git"
|
||||
|
||||
json_env = jsonencode({
|
||||
PGHOST = nubes_postgres.db2.state_out_flat["internalConnect.master"]
|
||||
PGPORT = "5432"
|
||||
PGUSER = nubes_postgres.db2.vault_secrets["adminUser"]
|
||||
PGPASSWORD = nubes_postgres.db2.vault_secrets["adminPass"]
|
||||
PGSSLMODE = "require"
|
||||
DATABASE_URL = format(
|
||||
"postgresql://%s:%s@%s:5432/postgres",
|
||||
nubes_postgres.db2.vault_secrets["adminUser"],
|
||||
nubes_postgres.db2.vault_secrets["adminPass"],
|
||||
nubes_postgres.db2.state_out_flat["internalConnect.master"]
|
||||
)
|
||||
})
|
||||
|
||||
resource_c_p_u = 300
|
||||
resource_memory = 256
|
||||
resource_instances = 1
|
||||
|
||||
depends_on = [nubes_postgres.db2]
|
||||
}
|
||||
*/
|
||||
@@ -0,0 +1,20 @@
|
||||
terraform {
|
||||
required_providers {
|
||||
nubes = {
|
||||
source = "terra.k8c.ru/nubes/nubes"
|
||||
version = "2.1.12"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
variable "api_token" {
|
||||
type = string
|
||||
sensitive = true
|
||||
description = "Nubes API token"
|
||||
}
|
||||
|
||||
provider "nubes" {
|
||||
api_token = var.api_token
|
||||
api_endpoint = "https://deck-api.ngcloud.ru/api/v1/index.cfm"
|
||||
}
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
resource "nubes_postgres" "db2" {
|
||||
# Основной Postgres-кластер для демо.
|
||||
resource_name = "pg-tst0"
|
||||
s3_uid = "6d6061cb-b0c1-44b9-8969-a70f08fe673c"
|
||||
# s3_uid = "s3-111805"
|
||||
resource_realm = "k8s-3.ext.nubes.ru"
|
||||
resource_instances = 1
|
||||
resource_memory = 512
|
||||
resource_c_p_u = 500
|
||||
resource_disk = "1"
|
||||
app_version = "17"
|
||||
json_parameters = jsonencode({
|
||||
# Выключаем подробные логи подключений в демо.
|
||||
log_connections = "off"
|
||||
log_disconnections = "off"
|
||||
})
|
||||
enable_pg_pooler_master = false
|
||||
enable_pg_pooler_slave = false
|
||||
allow_no_s_s_l = false
|
||||
auto_scale = false
|
||||
auto_scale_percentage = 10
|
||||
auto_scale_tech_window = 0
|
||||
auto_scale_quota_gb = "1"
|
||||
need_external_address_master = false
|
||||
}
|
||||
|
||||
output "pg_vault_secrets" {
|
||||
value = nubes_postgres.db2.vault_secrets
|
||||
sensitive = true
|
||||
}
|
||||
|
||||
resource "nubes_lucee" "app1" {
|
||||
# Lucee UI, который читает/пишет в Postgres.
|
||||
resource_name = "lucy1"
|
||||
resource_realm = nubes_postgres.db2.resource_realm
|
||||
domain = "web03"
|
||||
git_path = "https://gitea-naeel.giteak8s.services.ngcloud.ru/naeel/testlucee.git"
|
||||
|
||||
json_env = jsonencode({
|
||||
# JDBC datasource для Lucee.
|
||||
testds_class = "org.postgresql.Driver"
|
||||
testds_bundleName = "org.postgresql.jdbc"
|
||||
testds_bundleVersion = "42.6.0"
|
||||
testds_connectionString = "jdbc:postgresql://${nubes_postgres.db2.state_out_flat["internalConnect.master"]}:5432/postgres"
|
||||
testds_username = nubes_postgres.db2.vault_secrets["adminUser"]
|
||||
testds_password = nubes_postgres.db2.vault_secrets["adminPass"]
|
||||
testds_connectionLimit = "5"
|
||||
testds_liveTimeout = "15"
|
||||
testds_validate = "false"
|
||||
})
|
||||
|
||||
resource_c_p_u = 300
|
||||
resource_memory = 512
|
||||
resource_instances = 1
|
||||
app_version = "5.4"
|
||||
|
||||
depends_on = [nubes_postgres.db2]
|
||||
}
|
||||
|
||||
resource "nubes_nodejs" "app3" {
|
||||
# NodeJS демо, работающий с тем же Postgres.
|
||||
resource_name = "node_0"
|
||||
resource_realm = nubes_postgres.db2.resource_realm
|
||||
domain = "node"
|
||||
git_path = "https://gitea-naeel.giteak8s.services.ngcloud.ru/naeel/testnode.git"
|
||||
health_path = "/healthz"
|
||||
app_version = "23"
|
||||
|
||||
json_env = jsonencode({
|
||||
# Переменные подключения к Postgres.
|
||||
PGHOST = nubes_postgres.db2.state_out_flat["internalConnect.master"]
|
||||
PGPORT = "5432"
|
||||
PGUSER = nubes_postgres.db2.vault_secrets["adminUser"]
|
||||
PGPASSWORD = nubes_postgres.db2.vault_secrets["adminPass"]
|
||||
PGSSLMODE = "require"
|
||||
DATABASE_URL = format(
|
||||
"postgresql://%s:%s@%s:5432/postgres",
|
||||
nubes_postgres.db2.vault_secrets["adminUser"],
|
||||
nubes_postgres.db2.vault_secrets["adminPass"],
|
||||
nubes_postgres.db2.state_out_flat["internalConnect.master"]
|
||||
)
|
||||
})
|
||||
|
||||
resource_c_p_u = 300
|
||||
resource_memory = 256
|
||||
resource_instances = 1
|
||||
|
||||
depends_on = [nubes_postgres.db2]
|
||||
}
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
site/templates/
|
||||
site/static/
|
||||
venv/
|
||||
@@ -0,0 +1 @@
|
||||
disable=missing-function-docstring
|
||||
@@ -0,0 +1,14 @@
|
||||
# Базовый образ Python для Flask-приложения.
|
||||
FROM python:3.9-slim
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY requirements.txt .
|
||||
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
|
||||
COPY site /app/site
|
||||
|
||||
EXPOSE 5000
|
||||
|
||||
CMD ["python", "site/app.py"]
|
||||
@@ -0,0 +1,6 @@
|
||||
# Flask + Postgres Demo
|
||||
|
||||
Простое CRUD-приложение на Flask, которое пишет и читает из таблицы `nubes_test_table`.
|
||||
Если поле ввода пустое, вставляется запись "Это Flask сделал".
|
||||
|
||||
Примечание: таблица создается автоматически при первом запросе.
|
||||
@@ -0,0 +1,3 @@
|
||||
Flask==2.0.1
|
||||
Werkzeug==2.3.7
|
||||
psycopg2-binary==2.9.9
|
||||
@@ -0,0 +1,58 @@
|
||||
<cfcomponent displayname="Application" output="true">
|
||||
<!--- Базовая конфигурация Lucee и datasource. --->
|
||||
<cfset this.Name = "nubes-app-v8" />
|
||||
<cfset this.sessionmanagement = "Yes" />
|
||||
<cfset this.datasource = "testds" />
|
||||
<!--- Инициализируем datasource из переменных окружения. --->
|
||||
<cfset getDS(this.datasource) />
|
||||
|
||||
<!--- Собираем datasource из *_field переменных окружения. --->
|
||||
<cffunction name="getDS" access="private" returntype="void">
|
||||
<cfargument name="dsname" type="string" required="true"/>
|
||||
<cfset var system = createObject("java", "java.lang.System")/>
|
||||
<cfset var ds = {} />
|
||||
<cfloop list="class,connectionString,database,driver,host,port,type,url,username,password,bundleName,bundleVersion,connectionLimit,liveTimeout,validate" item="field">
|
||||
<cfset var envVal = system.getEnv("#arguments.dsname#_#field#") />
|
||||
<cfif isDefined("envVal") AND len(envVal)><cfset ds[field] = envVal /></cfif>
|
||||
</cfloop>
|
||||
<cfset this.datasources[arguments.dsname] = ds />
|
||||
</cffunction>
|
||||
|
||||
<!--- CRUD над таблицей nubes_test_table по POST запросам. --->
|
||||
<cffunction name="OnRequest" access="public" returntype="void" output="true">
|
||||
<cfargument name="template" type="string" required="true" />
|
||||
<cfset request.DS = this.datasource />
|
||||
|
||||
<!--- Обработка insert/update/delete через form.crud_action. --->
|
||||
<cfif CGI.REQUEST_METHOD EQ "POST" AND structKeyExists(form, "crud_action")>
|
||||
<cftry>
|
||||
<cfswitch expression="#form.crud_action#">
|
||||
<cfcase value="insert">
|
||||
<cfquery datasource="#request.DS#">
|
||||
INSERT INTO nubes_test_table (test_data) VALUES (<cfqueryparam value="#form.txt_content#" cfsqltype="cf_sql_varchar">)
|
||||
</cfquery>
|
||||
</cfcase>
|
||||
<cfcase value="update">
|
||||
<cfquery datasource="#request.DS#">
|
||||
UPDATE nubes_test_table SET test_data = <cfqueryparam value="#form.txt_content#" cfsqltype="cf_sql_varchar"> WHERE id = <cfqueryparam value="#form.id#" cfsqltype="cf_sql_integer">
|
||||
</cfquery>
|
||||
</cfcase>
|
||||
<cfcase value="delete">
|
||||
<cfquery datasource="#request.DS#">
|
||||
DELETE FROM nubes_test_table WHERE id = <cfqueryparam value="#form.id#" cfsqltype="cf_sql_integer">
|
||||
</cfquery>
|
||||
</cfcase>
|
||||
</cfswitch>
|
||||
<cflocation url="#CGI.SCRIPT_NAME#" addtoken="false">
|
||||
<cfcatch><cfset request.db_error = cfcatch.message /></cfcatch>
|
||||
</cftry>
|
||||
</cfif>
|
||||
|
||||
<!--- Гарантируем наличие таблицы при первом заходе. --->
|
||||
<cftry>
|
||||
<cfquery datasource="#request.DS#">CREATE TABLE IF NOT EXISTS nubes_test_table (id SERIAL PRIMARY KEY, test_data TEXT, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP);</cfquery>
|
||||
<cfcatch><cfset request.db_error = cfcatch.message /></cfcatch>
|
||||
</cftry>
|
||||
<cfinclude template="#arguments.template#" />
|
||||
</cffunction>
|
||||
</cfcomponent>
|
||||
@@ -0,0 +1,11 @@
|
||||
# Тестовое приложение by Terraform - Lucee & Postgres
|
||||
|
||||
### Что здесь можно делать:
|
||||
|
||||
* **Просмотр:** Список последних записей загружается автоматически при открытии страницы.
|
||||
* **Добавление:** Введите текст в верхнее поле и нажмите кнопку «Добавить», чтобы сохранить данные в базу.
|
||||
* **Редактирование:** Вы можете изменить текст любой записи прямо в таблице. Не забудьте нажать на кнопку с дискетой (💾), чтобы сохранить изменения.
|
||||
* **Удаление:** Нажмите на иконку корзины (🗑), чтобы навсегда удалить запись из базы данных.
|
||||
|
||||
Примечание: таблица создается автоматически при первом открытии страницы.
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
<!--- Редирект на основной UI экран. --->
|
||||
<cflocation addtoken="No" url="query.cfm##q"/>
|
||||
@@ -0,0 +1,77 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>Nubes | Управление данными</title>
|
||||
<link rel="icon" href="https://nubes.ru/themes/custom/nubes/images/nubes-ico.svg" type="image/svg+xml">
|
||||
<style>
|
||||
:root { --nubes-blue: #005BFF; --nubes-dark: #1A1A1A; --nubes-grey: #F8F9FA; --nubes-border: #E5E7EB; }
|
||||
body { font-family: 'Segoe UI', Tahoma, sans-serif; margin: 0; padding: 0; background: var(--nubes-grey); color: var(--nubes-dark); }
|
||||
.header-bg { position: sticky; top: 0; z-index: 1000; background: #fff; border-bottom: 1px solid var(--nubes-border); padding: 15px 0; box-shadow: 0 2px 10px rgba(0,0,0,0.05); }
|
||||
.container { max-width: 1000px; margin: auto; padding: 0 20px; }
|
||||
.header-content { display: flex; align-items: center; justify-content: space-between; }
|
||||
.logo { height: 40px; }
|
||||
.main-content { padding: 40px 0; }
|
||||
.card { background: #fff; padding: 32px; border-radius: 16px; box-shadow: 0 4px 20px rgba(0,0,0,0.04); }
|
||||
.btn { display: inline-flex; align-items: center; justify-content: center; cursor: pointer; padding: 12px 24px; border: none; border-radius: 8px; font-weight: 600; font-size: 14px; }
|
||||
.btn-primary { background: var(--nubes-blue); color: #fff; }
|
||||
/* Увеличенные кнопки действий */
|
||||
.btn-action { padding: 12px; background: #fff; border: 1px solid var(--nubes-border); border-radius: 8px; font-size: 24px; line-height: 1; cursor: pointer; min-width: 50px; }
|
||||
.btn-action:hover { background: var(--nubes-grey); border-color: var(--nubes-blue); }
|
||||
.input-group { display: flex; gap: 12px; margin-bottom: 32px; }
|
||||
input[type="text"] { flex-grow: 1; padding: 12px 16px; border: 1px solid var(--nubes-border); border-radius: 8px; font-size: 14px; }
|
||||
/* Полосатая таблица */
|
||||
table { width: 100%; border-collapse: collapse; }
|
||||
th { text-align: left; padding: 16px; font-size: 12px; text-transform: uppercase; color: #6B7280; border-bottom: 1px solid var(--nubes-border); }
|
||||
td { padding: 16px; border-bottom: 1px solid var(--nubes-border); }
|
||||
tbody tr:nth-child(even) { background-color: #FAFBFC; }
|
||||
tbody tr:hover { background-color: #F3F4F6; }
|
||||
.id-cell { font-family: monospace; color: #9CA3AF; width: 60px; }
|
||||
.actions-cell { display: flex; gap: 12px; width: 130px; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<!--- Верхняя панель с брендингом. --->
|
||||
<div class="header-bg">
|
||||
<div class="container header-content">
|
||||
<img src="https://nubes.ru/themes/custom/nubes_2025/logo.svg" alt="Nubes" class="logo">
|
||||
<div style="font-size: 14px; color: var(--nubes-blue); font-weight: 600;">Lucee + Postgres Demo</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="container main-content">
|
||||
<!--- Форма добавления записи. --->
|
||||
<div class="card">
|
||||
<form method="post" class="input-group">
|
||||
<input type="hidden" name="crud_action" value="insert">
|
||||
<input type="text" name="txt_content" placeholder="Новое сообщение..." required>
|
||||
<button type="submit" class="btn btn-primary">Добавить</button>
|
||||
</form>
|
||||
<!--- Читаем последние записи для отображения. --->
|
||||
<cfquery name="qGet" datasource="#request.DS#">SELECT * FROM nubes_test_table ORDER BY id DESC LIMIT 20</cfquery>
|
||||
<table>
|
||||
<thead><tr><th>ID</th><th>Содержимое</th><th>Действия</th></tr></thead>
|
||||
<tbody>
|
||||
<cfoutput query="qGet">
|
||||
<tr>
|
||||
<td class="id-cell">#id#</td>
|
||||
<td>
|
||||
<form method="post" id="upd_#id#" style="margin:0">
|
||||
<input type="hidden" name="crud_action" value="update"><input type="hidden" name="id" value="#id#">
|
||||
<input type="text" name="txt_content" value="#HTMLEditFormat(test_data)#" style="width:100%; border:none; background:transparent;">
|
||||
</form>
|
||||
</td>
|
||||
<td class="actions-cell">
|
||||
<button type="submit" form="upd_#id#" class="btn-action">💾</button>
|
||||
<form method="post" style="margin:0" onsubmit="return confirm('Удалить?')">
|
||||
<input type="hidden" name="crud_action" value="delete"><input type="hidden" name="id" value="#id#">
|
||||
<button type="submit" class="btn-action">🗑</button>
|
||||
</form>
|
||||
</td>
|
||||
</tr>
|
||||
</cfoutput>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1 @@
|
||||
again test hello
|
||||
@@ -0,0 +1 @@
|
||||
node_modules/
|
||||
@@ -0,0 +1,6 @@
|
||||
# NodeJS + Postgres Demo
|
||||
|
||||
Simple Node.js CRUD app that writes to `nubes_test_table` and renders a small HTML UI.
|
||||
If the input is empty, it inserts "Node did it".
|
||||
|
||||
Примечание: таблица создается автоматически, а дубликаты подряд отсекаются по таймауту.
|
||||
+6808
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,69 @@
|
||||
{
|
||||
"name": "loopback4-example-github",
|
||||
"version": "0.0.1",
|
||||
"description": "loopback4-example-github",
|
||||
"keywords": [
|
||||
"loopback-application",
|
||||
"loopback"
|
||||
],
|
||||
"main": "server.js",
|
||||
"engines": {
|
||||
"node": ">=10.16"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "lb-tsc",
|
||||
"build:watch": "lb-tsc --watch",
|
||||
"lint": "npm run eslint && npm run prettier:check",
|
||||
"lint:fix": "npm run eslint:fix && npm run prettier:fix",
|
||||
"prettier:cli": "lb-prettier \"**/*.ts\" \"**/*.js\"",
|
||||
"prettier:check": "npm run prettier:cli -- -l",
|
||||
"prettier:fix": "npm run prettier:cli -- --write",
|
||||
"eslint": "lb-eslint --report-unused-disable-directives .",
|
||||
"eslint:fix": "npm run eslint -- --fix",
|
||||
"pretest": "npm run rebuild",
|
||||
"test": "lb-mocha --allow-console-logs \"dist/__tests__\"",
|
||||
"posttest": "npm run lint",
|
||||
"test:dev": "lb-mocha --allow-console-logs dist/__tests__/**/*.js && npm run posttest",
|
||||
"docker:build": "docker build -t loopback4-example-github .",
|
||||
"docker:run": "docker run -p 3000:3000 -d loopback4-example-github",
|
||||
"premigrate": "npm run build",
|
||||
"migrate": "node ./dist/migrate",
|
||||
"preopenapi-spec": "npm run build",
|
||||
"openapi-spec": "node ./dist/openapi-spec",
|
||||
"start": "node server.js",
|
||||
"clean": "lb-clean dist *.tsbuildinfo .eslintcache",
|
||||
"rebuild": "npm run clean && npm run build"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": ""
|
||||
},
|
||||
"author": "Diana Lau <dhmlau@ca.ibm.com>",
|
||||
"license": "",
|
||||
"files": [
|
||||
"README.md",
|
||||
"dist",
|
||||
"src",
|
||||
"!*/__tests__"
|
||||
],
|
||||
"dependencies": {
|
||||
"@loopback/boot": "^3.4.1",
|
||||
"@loopback/core": "^2.16.1",
|
||||
"@loopback/repository": "^3.7.0",
|
||||
"@loopback/rest": "^9.3.1",
|
||||
"@loopback/rest-explorer": "^3.3.1",
|
||||
"@loopback/service-proxy": "^3.2.1",
|
||||
"loopback-connector-rest": "^3.7.0",
|
||||
"pg": "^8.18.0",
|
||||
"tslib": "^2.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@loopback/build": "^6.4.1",
|
||||
"@loopback/eslint-config": "^10.2.1",
|
||||
"@loopback/testlab": "^3.4.1",
|
||||
"@types/node": "^10.17.60",
|
||||
"eslint": "^7.28.0",
|
||||
"source-map-support": "^0.5.19",
|
||||
"typescript": "~4.3.2"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
|
||||
<head>
|
||||
<title>loopback4-example-github</title>
|
||||
|
||||
<meta charset="utf-8">
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=edge">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<link rel="shortcut icon" type="image/x-icon" href="https://loopback.io/favicon.ico">
|
||||
|
||||
<style>
|
||||
h3 {
|
||||
margin-left: 25px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
a, a:visited {
|
||||
color: #3f5dff;
|
||||
}
|
||||
|
||||
h3 a {
|
||||
margin-left: 10px;
|
||||
}
|
||||
|
||||
a:hover, a:focus, a:active {
|
||||
color: #001956;
|
||||
}
|
||||
|
||||
.power {
|
||||
position: absolute;
|
||||
bottom: 25px;
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
}
|
||||
|
||||
.info {
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
left: 50%;
|
||||
transform: translate(-50%, -50%)
|
||||
}
|
||||
|
||||
.info h1 {
|
||||
text-align: center;
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
.info p {
|
||||
text-align: center;
|
||||
margin-bottom: 3em;
|
||||
margin-top: 1em;
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
body {
|
||||
background-color: rgb(29, 30, 32);
|
||||
color: white;
|
||||
}
|
||||
|
||||
a, a:visited {
|
||||
color: #4990e2;
|
||||
}
|
||||
|
||||
a:hover, a:focus, a:active {
|
||||
color: #2b78ff;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div class="info">
|
||||
<h1>loopback4-example-github</h1>
|
||||
<p>Version 1.0.0</p>
|
||||
|
||||
<h3>OpenAPI spec: <a href="/openapi.json">/openapi.json</a></h3>
|
||||
<h3>API Explorer: <a href="/explorer">/explorer</a></h3>
|
||||
</div>
|
||||
|
||||
<footer class="power">
|
||||
<a href="https://loopback.io" target="_blank">
|
||||
<img src="https://loopback.io/images/branding/powered-by-loopback/blue/powered-by-loopback-sm.png" />
|
||||
</a>
|
||||
</footer>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
@@ -0,0 +1,204 @@
|
||||
const http = require("http");
|
||||
const { URL } = require("url");
|
||||
const { Pool } = require("pg");
|
||||
|
||||
// Конфигурация Postgres, DATABASE_URL имеет приоритет.
|
||||
function buildPgConfig() {
|
||||
if (process.env.DATABASE_URL) {
|
||||
return {
|
||||
connectionString: process.env.DATABASE_URL,
|
||||
ssl: process.env.PGSSLMODE === "require" ? { rejectUnauthorized: false } : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
host: process.env.PGHOST,
|
||||
port: Number(process.env.PGPORT || "5432"),
|
||||
user: process.env.PGUSER,
|
||||
password: process.env.PGPASSWORD,
|
||||
database: process.env.PGDATABASE || "postgres",
|
||||
ssl: process.env.PGSSLMODE === "require" ? { rejectUnauthorized: false } : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
// Общий пул подключений.
|
||||
const pool = new Pool(buildPgConfig());
|
||||
|
||||
// Таблица для демо создается автоматически.
|
||||
async function ensureTable() {
|
||||
await pool.query(
|
||||
"CREATE TABLE IF NOT EXISTS nubes_test_table (id SERIAL PRIMARY KEY, test_data TEXT, created_at TIMESTAMP DEFAULT NOW())"
|
||||
);
|
||||
}
|
||||
|
||||
// Простой парсер application/x-www-form-urlencoded.
|
||||
function parseForm(body) {
|
||||
return body
|
||||
.split("&")
|
||||
.map((pair) => pair.split("="))
|
||||
.reduce((acc, [key, value]) => {
|
||||
acc[decodeURIComponent(key)] = decodeURIComponent((value || "").replace(/\+/g, " "));
|
||||
return acc;
|
||||
}, {});
|
||||
}
|
||||
|
||||
// Рендер HTML-страницы с CRUD-формами.
|
||||
function renderPage(rows, error) {
|
||||
const errorHtml = error ? `<p style="color:red">${error}</p>` : "";
|
||||
const rowsHtml = rows
|
||||
.map(
|
||||
(row) => `
|
||||
<tr>
|
||||
<td>${row.id}</td>
|
||||
<td>
|
||||
<form method="POST" action="/update">
|
||||
<input type="hidden" name="id" value="${row.id}">
|
||||
<input type="text" name="txt_content" value="${row.test_data}">
|
||||
<button type="submit">save</button>
|
||||
</form>
|
||||
</td>
|
||||
<td>
|
||||
<form method="POST" action="/delete" onsubmit="return confirm('Delete?')">
|
||||
<input type="hidden" name="id" value="${row.id}">
|
||||
<button type="submit">delete</button>
|
||||
</form>
|
||||
</td>
|
||||
</tr>`
|
||||
)
|
||||
.join("");
|
||||
|
||||
return `<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>NodeJS + Postgres Demo</title>
|
||||
<link rel="icon" href="https://nubes.ru/themes/custom/nubes/images/nubes-ico.svg" type="image/svg+xml">
|
||||
<style>
|
||||
:root { --nubes-blue: #005BFF; --nubes-dark: #1A1A1A; --nubes-grey: #F8F9FA; --nubes-border: #E5E7EB; }
|
||||
body { font-family: 'Segoe UI', Tahoma, sans-serif; margin: 0; padding: 0; background: var(--nubes-grey); color: var(--nubes-dark); }
|
||||
.header-bg { position: sticky; top: 0; z-index: 1000; background: #fff; border-bottom: 1px solid var(--nubes-border); padding: 15px 0; box-shadow: 0 2px 10px rgba(0,0,0,0.05); }
|
||||
.container { max-width: 1000px; margin: auto; padding: 0 20px; }
|
||||
.header-content { display: flex; align-items: center; justify-content: space-between; }
|
||||
.logo { height: 40px; }
|
||||
.main-content { padding: 40px 0; }
|
||||
.card { background: #fff; padding: 32px; border-radius: 16px; box-shadow: 0 4px 20px rgba(0,0,0,0.04); }
|
||||
.btn { display: inline-flex; align-items: center; justify-content: center; cursor: pointer; padding: 12px 24px; border: none; border-radius: 8px; font-weight: 600; font-size: 14px; }
|
||||
.btn-primary { background: var(--nubes-blue); color: #fff; }
|
||||
.btn-action { padding: 12px; background: #fff; border: 1px solid var(--nubes-border); border-radius: 8px; font-size: 18px; line-height: 1; cursor: pointer; min-width: 44px; }
|
||||
.btn-action:hover { background: var(--nubes-grey); border-color: var(--nubes-blue); }
|
||||
.input-group { display: flex; gap: 12px; margin-bottom: 32px; }
|
||||
input[type="text"] { flex-grow: 1; width: 100%; padding: 12px 16px; border: 1px solid var(--nubes-border); border-radius: 8px; font-size: 14px; }
|
||||
table { width: 100%; border-collapse: collapse; }
|
||||
th { text-align: left; padding: 16px; font-size: 12px; text-transform: uppercase; color: #6B7280; border-bottom: 1px solid var(--nubes-border); }
|
||||
td { padding: 16px; border-bottom: 1px solid var(--nubes-border); }
|
||||
tbody tr:nth-child(even) { background-color: #FAFBFC; }
|
||||
tbody tr:hover { background-color: #F3F4F6; }
|
||||
.id-cell { font-family: monospace; color: #9CA3AF; width: 60px; }
|
||||
.actions-cell { display: flex; gap: 12px; width: 130px; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="header-bg">
|
||||
<div class="container header-content">
|
||||
<img src="https://nubes.ru/themes/custom/nubes_2025/logo.svg" alt="Nubes" class="logo">
|
||||
<div style="font-size: 14px; color: var(--nubes-blue); font-weight: 600;">NodeJS + Postgres Demo</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="container main-content">
|
||||
<div class="card">
|
||||
${errorHtml}
|
||||
<form method="POST" action="/add" class="input-group" onsubmit="const btn=this.querySelector('button'); if(btn){btn.disabled=true; btn.textContent='Adding...';}">
|
||||
<input type="text" name="txt_content" placeholder="New message" required>
|
||||
<button type="submit" class="btn btn-primary">Add</button>
|
||||
</form>
|
||||
<table>
|
||||
<thead><tr><th>ID</th><th>Content</th><th>Actions</th></tr></thead>
|
||||
<tbody>
|
||||
${rowsHtml}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>`;
|
||||
}
|
||||
|
||||
// Маршруты: /, /add, /update, /delete, /healthz.
|
||||
async function handleRequest(req, res) {
|
||||
const url = new URL(req.url, `http://${req.headers.host}`);
|
||||
|
||||
if (req.method === "GET" && url.pathname === "/healthz") {
|
||||
res.writeHead(200, { "Content-Type": "text/plain" });
|
||||
res.end("ok");
|
||||
return;
|
||||
}
|
||||
|
||||
if (req.method === "GET" && url.pathname === "/") {
|
||||
try {
|
||||
await ensureTable();
|
||||
const { rows } = await pool.query(
|
||||
"SELECT id, test_data FROM nubes_test_table ORDER BY id DESC LIMIT 20"
|
||||
);
|
||||
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
|
||||
res.end(renderPage(rows));
|
||||
} catch (err) {
|
||||
res.writeHead(500, { "Content-Type": "text/html; charset=utf-8" });
|
||||
res.end(renderPage([], err.message));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (req.method === "POST" && ["/add", "/update", "/delete"].includes(url.pathname)) {
|
||||
let body = "";
|
||||
req.on("data", (chunk) => {
|
||||
body += chunk;
|
||||
});
|
||||
req.on("end", async () => {
|
||||
const form = parseForm(body);
|
||||
try {
|
||||
await ensureTable();
|
||||
if (url.pathname === "/add") {
|
||||
const content = form.txt_content || "Node did it";
|
||||
// Защита от быстрых дублей подряд.
|
||||
const { rows: lastRows } = await pool.query(
|
||||
"SELECT test_data, created_at FROM nubes_test_table ORDER BY id DESC LIMIT 1"
|
||||
);
|
||||
const last = lastRows[0];
|
||||
const isDuplicate =
|
||||
last &&
|
||||
last.test_data === content &&
|
||||
Date.now() - new Date(last.created_at).getTime() < 3000;
|
||||
|
||||
if (!isDuplicate) {
|
||||
await pool.query("INSERT INTO nubes_test_table (test_data) VALUES ($1)", [content]);
|
||||
}
|
||||
}
|
||||
if (url.pathname === "/update") {
|
||||
await pool.query("UPDATE nubes_test_table SET test_data=$1 WHERE id=$2", [
|
||||
form.txt_content || "",
|
||||
form.id,
|
||||
]);
|
||||
}
|
||||
if (url.pathname === "/delete") {
|
||||
await pool.query("DELETE FROM nubes_test_table WHERE id=$1", [form.id]);
|
||||
}
|
||||
res.writeHead(303, { Location: "/" });
|
||||
res.end();
|
||||
} catch (err) {
|
||||
res.writeHead(500, { "Content-Type": "text/html; charset=utf-8" });
|
||||
res.end(renderPage([], err.message));
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
res.writeHead(404, { "Content-Type": "text/plain" });
|
||||
res.end("Not found");
|
||||
}
|
||||
|
||||
const port = process.env.PORT || 3000;
|
||||
const server = http.createServer(handleRequest);
|
||||
|
||||
server.listen(port, () => {
|
||||
console.log(`Server running on port ${port}`);
|
||||
});
|
||||
@@ -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';
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"$schema": "http://json.schemastore.org/tsconfig",
|
||||
"extends": "@loopback/build/config/tsconfig.common.json",
|
||||
"compilerOptions": {
|
||||
"outDir": "dist",
|
||||
"rootDir": "src"
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
Reference in New Issue
Block a user