Compare commits
88 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| cee4ea98f5 | |||
| cdafc4bd79 | |||
| a9485a4d0a | |||
| d0877dd0a9 | |||
| bad631eeae | |||
| 5915ae2733 | |||
| ab7047b9cd | |||
| 23f87d376a | |||
| ffe9b66886 | |||
| c85b689aed | |||
| 22735a9ea6 | |||
| 9367999ef2 | |||
| d42824d41a | |||
| 7d2186860c | |||
| 99dfaddf04 | |||
| 45b9ac1281 | |||
| 8d0d804923 | |||
| fe91ce6ed3 | |||
| a6c627a178 | |||
| 763ddd8bd7 | |||
| 3016a6da70 | |||
| f0b2433b59 | |||
| b92c75b131 | |||
| 4ca4fd9559 | |||
| 3deacd7e80 | |||
| a0f44eacce | |||
| 87eeb7f553 | |||
| 2d06d34c7c | |||
| 3f8f8fa773 | |||
| 5f72eae55c | |||
| 96e580e56a | |||
| ca12844268 | |||
| 76fa0649f2 | |||
| 3b4ac12582 | |||
| eb55709be5 | |||
| 446b49c9a0 | |||
| 36c309a69c | |||
| 3f55ad71cf | |||
| f8ec31ff7e | |||
| 739311928f | |||
| 78cda0fe50 | |||
| 7d40005e7d | |||
| 855de182ea | |||
| a96e7d9344 | |||
| 2e2799f2d3 | |||
| da0c4bbd05 | |||
| 6e75012376 | |||
| 5488d7a8d7 | |||
| 3bb0b2aa29 | |||
| c30cf80fc6 | |||
| 62afef402f | |||
| db61357a0f | |||
| fd1ba06b45 | |||
| 1b9e35539e | |||
| 19a4051159 | |||
| 6fee9090e7 | |||
| 5c9ee58f41 | |||
| f56f1e859b | |||
| 8504017cf7 | |||
| 5d61cf3cdc | |||
| 5d721ddea6 | |||
| 733927966a | |||
| c38f700e93 | |||
| f59fc2e8e0 | |||
| 70712b9a87 | |||
| 4ff507b0fa | |||
| 7ebced9304 | |||
| 028bcc99dd | |||
| 74869993b0 | |||
| bac87e9c33 | |||
| afa35939fa | |||
| 1c32e42b47 | |||
| c72c933c0b | |||
| 3c7add4807 | |||
| 3d73e6d612 | |||
| da62d64727 | |||
| 7de1083fdd | |||
| 1f4eae697d | |||
| 1b3a247d9d | |||
| 2f6a2ad94a | |||
| 1a847ab9fe | |||
| 67a1c744ae | |||
| f919af4248 | |||
| 4a74bac620 | |||
| 2710b0e014 | |||
| de57c6e18a | |||
| 68b96dfb82 | |||
| 9dfe5207d9 |
@@ -0,0 +1,10 @@
|
|||||||
|
.git*
|
||||||
|
|
||||||
|
tools*
|
||||||
|
mysql*
|
||||||
|
letsencrypt*
|
||||||
|
test*
|
||||||
|
|
||||||
|
.env*
|
||||||
|
.github*
|
||||||
|
LICENSE*
|
||||||
@@ -1,10 +1,22 @@
|
|||||||
WEB_PORT=3100
|
WEB_PORT=3100
|
||||||
|
|
||||||
DB_HOSTNAME=database
|
WEB_ORIGIN=http://localhost:3001
|
||||||
|
|
||||||
|
DB_HOSTNAME=localhost
|
||||||
|
DB_PORTNAME=3306
|
||||||
|
|
||||||
DB_DATABASE=news
|
DB_DATABASE=news
|
||||||
DB_USERNAME=news
|
DB_USERNAME=news
|
||||||
DB_PASSWORD=charizard
|
DB_PASSWORD=venusaur
|
||||||
|
|
||||||
|
# Select a "TZ database name" that suits your needs: https://en.wikipedia.org/wiki/List_of_tz_database_time_zones
|
||||||
DB_TIMEZONE=Australia/Sydney
|
DB_TIMEZONE=Australia/Sydney
|
||||||
|
|
||||||
QUERY_LIMIT=10
|
# Give this any value to enable database logging (such as "true")
|
||||||
QUERY_KEY=key
|
DB_LOGGING=
|
||||||
|
|
||||||
|
# Make sure this value matches the system that you connect to
|
||||||
|
SECRET_ACCESS=access
|
||||||
|
|
||||||
|
# Select the default number of articles returned by a GET request
|
||||||
|
PAGE_SIZE=10
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
# These are supported funding model platforms
|
||||||
|
|
||||||
|
patreon: krgamestudios
|
||||||
|
ko_fi: krgamestudios
|
||||||
|
custom: ["https://www.paypal.com/donate/?hosted_button_id=73Q82T2ZHV8AA"]
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
# https://docs.github.com/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file
|
||||||
|
|
||||||
|
version: 2
|
||||||
|
updates:
|
||||||
|
- package-ecosystem: "npm"
|
||||||
|
directory: "/"
|
||||||
|
schedule:
|
||||||
|
interval: "weekly"
|
||||||
|
|
||||||
|
|
||||||
@@ -2,17 +2,40 @@ name: Publish Docker image
|
|||||||
on:
|
on:
|
||||||
release:
|
release:
|
||||||
types: [ published ]
|
types: [ published ]
|
||||||
|
push:
|
||||||
|
tags:
|
||||||
|
- v1.*
|
||||||
|
workflow_dispatch:
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
push_to_registry:
|
push_to_registry:
|
||||||
name: Push Docker image to Docker Hub
|
name: Push Docker Image to Docker Hub
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- name: Check out the repo
|
- name: Checkout
|
||||||
uses: actions/checkout@v2
|
uses: actions/checkout@v5
|
||||||
- name: Push to Docker Hub
|
|
||||||
uses: docker/build-push-action@v1
|
- name: Setup QEMU
|
||||||
|
uses: docker/setup-qemu-action@v3
|
||||||
|
|
||||||
|
- name: Set up Docker Buildx
|
||||||
|
uses: docker/setup-buildx-action@v3
|
||||||
|
|
||||||
|
- name: Get Smart Tag
|
||||||
|
id: prepare
|
||||||
|
uses: Surgo/docker-smart-tag-action@v1
|
||||||
|
with:
|
||||||
|
docker_image: krgamestudios/news-server
|
||||||
|
|
||||||
|
- name: Login to DockerHub
|
||||||
|
uses: docker/login-action@v3
|
||||||
with:
|
with:
|
||||||
username: ${{ secrets.DOCKER_USERNAME }}
|
username: ${{ secrets.DOCKER_USERNAME }}
|
||||||
password: ${{ secrets.DOCKER_PASSWORD }}
|
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||||
repository: krgamestudios/news-server
|
|
||||||
tag_with_ref: true
|
- name: Push to Docker Hub
|
||||||
|
uses: docker/build-push-action@v6
|
||||||
|
with:
|
||||||
|
push: true
|
||||||
|
tags: ${{ steps.prepare.outputs.tag }}
|
||||||
|
platforms: amd64,arm
|
||||||
|
|||||||
+4
-1
@@ -104,4 +104,7 @@ dist
|
|||||||
.tern-port
|
.tern-port
|
||||||
|
|
||||||
# Docker generated files and folders
|
# Docker generated files and folders
|
||||||
data/
|
letsencrypt/
|
||||||
|
mysql/
|
||||||
|
docker-compose.yml
|
||||||
|
startup.sql
|
||||||
|
|||||||
+5
-13
@@ -1,18 +1,10 @@
|
|||||||
FROM node:15
|
|
||||||
|
|
||||||
# Change working directory
|
FROM node:22-bookworm-slim
|
||||||
WORKDIR "/app"
|
WORKDIR "/app"
|
||||||
|
COPY package*.json /app
|
||||||
# Copy package.json and package-lock.json
|
RUN npm install --omit=dev
|
||||||
COPY package*.json ./
|
|
||||||
|
|
||||||
# Install npm production packages
|
|
||||||
RUN npm install --production
|
|
||||||
|
|
||||||
COPY . /app
|
COPY . /app
|
||||||
|
|
||||||
EXPOSE 3100
|
EXPOSE 3100
|
||||||
|
|
||||||
USER node
|
USER node
|
||||||
|
ENTRYPOINT ["bash", "-c"]
|
||||||
ENTRYPOINT ["npm", "start"]
|
CMD ["sleep 10 && npm start"]
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
Copyright (c) 2021 Kayne Ruse, KR Game Studios
|
Copyright (c) 2021-2023 Kayne Ruse, KR Game Studios
|
||||||
|
|
||||||
This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software.
|
This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software.
|
||||||
|
|
||||||
|
|||||||
@@ -2,102 +2,268 @@
|
|||||||
|
|
||||||
An API centric news server. Uses Sequelize and mariaDB by default.
|
An API centric news server. Uses Sequelize and mariaDB by default.
|
||||||
|
|
||||||
|
This server is available via docker hub at krgamestudios/news-server.
|
||||||
|
|
||||||
# Setup
|
# Setup
|
||||||
|
|
||||||
This currently runs in docker. It might need to run twice the first time.
|
There are multiple ways to run this app - it can run on it's own via `npm start` (for production) or `npm run dev` (for development). it can also run inside docker using `docker compose up --build` - run `node configure-script.js` to generate docker-compose.yml and startup.sql.
|
||||||
|
|
||||||
|
To generate an authorization token, use [auth-server](https://github.com/krgamestudios/auth-server). A public-facing development auth-server is available here (tokens are valid for 10 minutes):
|
||||||
|
|
||||||
|
```
|
||||||
|
POST https://dev-auth.krgamestudios.com/auth/login HTTP/1.1
|
||||||
|
Content-Type: application/json
|
||||||
|
|
||||||
|
{
|
||||||
|
"email": "example@example.com",
|
||||||
|
"password": "helloworld"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
# API
|
# API
|
||||||
|
|
||||||
|
### `GET /news/:id?`
|
||||||
|
|
||||||
|
Get either an array of articles (newest first), or a specified article if the optional "id" parameter is given.
|
||||||
|
|
||||||
|
#### Response Body
|
||||||
|
|
||||||
|
```jsonc
|
||||||
|
[{
|
||||||
|
// [Number] index of the article
|
||||||
|
"index": index,
|
||||||
|
|
||||||
|
// [String] author of the article
|
||||||
|
"author": author,
|
||||||
|
|
||||||
|
// [String] raw body of the article
|
||||||
|
"body": body,
|
||||||
|
|
||||||
|
// [Number] number of times this article has been edited
|
||||||
|
"edits": edits,
|
||||||
|
|
||||||
|
// [String] body of the article rendered as HTML
|
||||||
|
"rendered": rendered,
|
||||||
|
|
||||||
|
// [String] title of the article
|
||||||
|
"title": title,
|
||||||
|
|
||||||
|
// [Date] time article was created
|
||||||
|
"createdAt": createdAt,
|
||||||
|
|
||||||
|
// [Date] time article was updated
|
||||||
|
"updatedAt": updatedAt,
|
||||||
|
}]
|
||||||
```
|
```
|
||||||
//NOTE: GET will return null if a specific article can't be found
|
|
||||||
//NOTE: you can add a "limit" query parameter to change the default limit
|
|
||||||
GET /news?limit=10
|
|
||||||
|
|
||||||
//get latest news, up to a default limit, or specify the index "id"
|
#### Available Query Parameters
|
||||||
GET /news/:id
|
|
||||||
|
|
||||||
//get the news starting from the beginning, up to a default limit, or specify the index "id"
|
- `fields`
|
||||||
GET /news/archive/:id
|
- TYPE: `string`
|
||||||
|
A comma separated list of the field names you want returning, (index will always be returned)
|
||||||
|
- `page`
|
||||||
|
- TYPE: `number`
|
||||||
|
The current page you want returning
|
||||||
|
- `page_size`
|
||||||
|
- TYPE: `number`
|
||||||
|
The number of results to return. This superseeds the `PAGE_SIZE` environment variable for the query
|
||||||
|
|
||||||
//result (if only a single article is specified, returns just that article rather than an array):
|
> **NOTE**
|
||||||
[
|
> If a specific article is requested, then just that article is returned rather than an array
|
||||||
{
|
|
||||||
"index": index, //absolute index of the result
|
|
||||||
"title": title, //title of the article
|
|
||||||
"author": author, //author of the aricle
|
|
||||||
"body": body, //body of the article
|
|
||||||
"edits": edits //number of times this article has been edited
|
|
||||||
"createdAt": createdAt //time created
|
|
||||||
"updatedAt": updatedAt //time updated
|
|
||||||
},
|
|
||||||
...
|
|
||||||
]
|
|
||||||
|
|
||||||
//get the latest titles, up to a default limit, or specify the index "id"
|
### `GET /news/archive/:id?`
|
||||||
GET /news/titles/:id
|
|
||||||
|
|
||||||
//get the titles starting from the beginning, up to a default limit, or specify the index "id"
|
Get either an array of articles (oldest first), or a specified article if the optional "id" parameter is given.
|
||||||
GET /news/archive/titles/:id
|
|
||||||
|
|
||||||
//result (if only a single article is specified, returns just that article rather than an array):
|
#### Response Body
|
||||||
[
|
|
||||||
{
|
|
||||||
"index": index, //absolute index of the result
|
|
||||||
"title": title, //title of the article
|
|
||||||
"author": author //author of the article
|
|
||||||
"edits": edits //number of times this article has been edited
|
|
||||||
"createdAt": createdAt //time created
|
|
||||||
"updatedAt": updatedAt //time updated
|
|
||||||
},
|
|
||||||
...
|
|
||||||
]
|
|
||||||
|
|
||||||
//send a formatted JSON object, returns new index on success, or error on failure
|
```jsonc
|
||||||
POST /news
|
[{
|
||||||
|
// [Number] index of the article
|
||||||
|
"index": index,
|
||||||
|
|
||||||
//arguments:
|
// [String] author of the article
|
||||||
|
"author": author,
|
||||||
|
|
||||||
|
// [String] raw body of the article
|
||||||
|
"body": body,
|
||||||
|
|
||||||
|
// [Number] number of times this article has been edited
|
||||||
|
"edits": edits,
|
||||||
|
|
||||||
|
// [String] body of the article rendered as HTML
|
||||||
|
"rendered": rendered,
|
||||||
|
|
||||||
|
// [String] title of the article
|
||||||
|
"title": title,
|
||||||
|
|
||||||
|
// [Date] time article was created
|
||||||
|
"createdAt": createdAt,
|
||||||
|
|
||||||
|
// [Date] time article was updated
|
||||||
|
"updatedAt": updatedAt,
|
||||||
|
}]
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Available Query Parameters
|
||||||
|
|
||||||
|
- `fields`
|
||||||
|
- TYPE: `string`
|
||||||
|
A comma separated list of the field names you want returning, (index will always be returned)
|
||||||
|
- `page`
|
||||||
|
- TYPE: `number`
|
||||||
|
The current page you want returning
|
||||||
|
- `page_size`
|
||||||
|
- TYPE: `number`
|
||||||
|
The number of results to return. This superseeds the `PAGE_SIZE` environment variable for the query
|
||||||
|
|
||||||
|
> **NOTE**
|
||||||
|
> If a specific article is requested, then just that article is returned rather than an array
|
||||||
|
|
||||||
|
### `GET /news/metadata/:id?`
|
||||||
|
|
||||||
|
Get either an array of metadata (newest first), or a specified article's metadata if the optional "id" parameter is given.
|
||||||
|
|
||||||
|
#### Response Body
|
||||||
|
|
||||||
|
```jsonc
|
||||||
|
[{
|
||||||
|
// [Number] index of the article
|
||||||
|
"index": index,
|
||||||
|
|
||||||
|
// [String] author of the article
|
||||||
|
"author": author,
|
||||||
|
|
||||||
|
// [Number] number of times this article has been edited
|
||||||
|
"edits": edits,
|
||||||
|
|
||||||
|
// [String] title of the article
|
||||||
|
"title": title,
|
||||||
|
|
||||||
|
// [Date] time article was created
|
||||||
|
"createdAt": createdAt,
|
||||||
|
|
||||||
|
// [Date] time article was updated
|
||||||
|
"updatedAt": updatedAt,
|
||||||
|
}]
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Available Query Parameters
|
||||||
|
|
||||||
|
- `fields`
|
||||||
|
- TYPE: `string`
|
||||||
|
A comma separated list of the field names you want returning, (index will always be returned)
|
||||||
|
- `page`
|
||||||
|
- TYPE: `number`
|
||||||
|
The current page you want returning
|
||||||
|
- `page_size`
|
||||||
|
- TYPE: `number`
|
||||||
|
The number of results to return. This superseeds the `PAGE_SIZE` environment variable for the query
|
||||||
|
|
||||||
|
> **NOTE**
|
||||||
|
> If a specific article is requested, then just that article is returned rather than an array
|
||||||
|
|
||||||
|
### `GET /news/archive/metadata/:id?`
|
||||||
|
|
||||||
|
Get either an array of metadata (oldest first), or a specified article's metadata if the optional "id" parameter is given.
|
||||||
|
|
||||||
|
#### Response Body
|
||||||
|
|
||||||
|
```jsonc
|
||||||
|
[{
|
||||||
|
// [Number] index of the article
|
||||||
|
"index": index,
|
||||||
|
|
||||||
|
// [String] author of the article
|
||||||
|
"author": author,
|
||||||
|
|
||||||
|
// [Number] number of times this article has been edited
|
||||||
|
"edits": edits,
|
||||||
|
|
||||||
|
// [String] title of the article
|
||||||
|
"title": title,
|
||||||
|
|
||||||
|
// [Date] time article was created
|
||||||
|
"createdAt": createdAt,
|
||||||
|
|
||||||
|
// [Date] time article was updated
|
||||||
|
"updatedAt": updatedAt,
|
||||||
|
}]
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Available Query Parameters
|
||||||
|
|
||||||
|
- `fields`
|
||||||
|
- TYPE: `string`
|
||||||
|
A comma separated list of the field names you want returning, (index will always be returned)
|
||||||
|
- `page`
|
||||||
|
- TYPE: `number`
|
||||||
|
The current page you want returning
|
||||||
|
- `page_size`
|
||||||
|
- TYPE: `number`
|
||||||
|
The number of results to return. This supersedes the `PAGE_SIZE` environment variable for the query
|
||||||
|
|
||||||
|
> **NOTE**
|
||||||
|
> If a specific article is requested, then just that article is returned rather than an array
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### `POST /news`
|
||||||
|
|
||||||
|
> **IMPORTANT**
|
||||||
|
> Requires valid JWT Authorization header (Authorization: Bearer XXX)
|
||||||
|
|
||||||
|
Create a new article resource, returns either the new article's index on success, or an error on failure.
|
||||||
|
|
||||||
|
#### Request Body
|
||||||
|
|
||||||
|
```jsonc
|
||||||
{
|
{
|
||||||
"key": key //the whitelist key, allows access to the POST routes
|
// [String] OPTIONAL: title of the article
|
||||||
"title": title //title of the article
|
"title": title,
|
||||||
"author": author //author of the article
|
|
||||||
"body": body //body of the article
|
|
||||||
}
|
|
||||||
|
|
||||||
//result:
|
// [String] OPTIONAL: author of the article
|
||||||
{
|
"author": author,
|
||||||
"ok": ok //true on success, otherwise false
|
|
||||||
"index": index //new index of the article, or undefined
|
|
||||||
"error": error //error encountered, or undefined
|
|
||||||
}
|
|
||||||
|
|
||||||
//similar to `POST /news`, but allows overwriting an existing article
|
// [String] OPTIONAL: body of the article
|
||||||
PATCH /news/:id
|
"body": body,
|
||||||
|
|
||||||
//arguments:
|
|
||||||
{
|
|
||||||
"key": key //the whitelist key, allows access to the PATCH routes
|
|
||||||
"title": title //title of the article
|
|
||||||
"author": author //author of the article
|
|
||||||
"body": body //body of the article
|
|
||||||
}
|
|
||||||
|
|
||||||
//result:
|
|
||||||
{
|
|
||||||
"ok": ok //true on success, otherwise false
|
|
||||||
"error": error //error encountered, or undefined
|
|
||||||
}
|
|
||||||
|
|
||||||
//remove an article from the news feed
|
|
||||||
DELETE /news/:id
|
|
||||||
|
|
||||||
//arguments:
|
|
||||||
{
|
|
||||||
"key": key //the whitelist key, allows access to the DELETE routes
|
|
||||||
}
|
|
||||||
|
|
||||||
//result:
|
|
||||||
{
|
|
||||||
"ok": ok //true on success, otherwise false
|
|
||||||
"error": error //error encountered, or undefined
|
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
#### Response Body
|
||||||
|
|
||||||
|
```jsonc
|
||||||
|
{
|
||||||
|
// [Number]: new index of the article
|
||||||
|
"index": index,
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### `PATCH /news/:id`
|
||||||
|
|
||||||
|
> **IMPORTANT**
|
||||||
|
> Requires valid JWT Authorization header (Authorization: Bearer XXX)
|
||||||
|
|
||||||
|
Update an existing article resource, returns either status code 200 on success, or an error status on failure.
|
||||||
|
|
||||||
|
#### Request Body
|
||||||
|
|
||||||
|
```jsonc
|
||||||
|
{
|
||||||
|
// [String] OPTIONAL: title of the article
|
||||||
|
"title": title,
|
||||||
|
|
||||||
|
// [String] OPTIONAL: author of the article
|
||||||
|
"author": author,
|
||||||
|
|
||||||
|
// [String] OPTIONAL: body of the article
|
||||||
|
"body": body,
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### `DELETE /news/:id`
|
||||||
|
|
||||||
|
> **IMPORTANT**
|
||||||
|
> Requires valid JWT Authorization header (Authorization: Bearer XXX)
|
||||||
|
|
||||||
|
Remove an existing article resource from the news feed, returns either status code 200 on success, or an error status on failure.
|
||||||
@@ -0,0 +1,162 @@
|
|||||||
|
//setup
|
||||||
|
const readline = require('readline');
|
||||||
|
const fs = require('fs');
|
||||||
|
const crypto = require("crypto");
|
||||||
|
|
||||||
|
const uuid = (bytes = 16) => crypto.randomBytes(bytes).toString("hex");
|
||||||
|
|
||||||
|
const rl = readline.createInterface({
|
||||||
|
input: process.stdin,
|
||||||
|
output: process.stdout,
|
||||||
|
terminal: false
|
||||||
|
});
|
||||||
|
|
||||||
|
//manually promisify this (util didn't work)
|
||||||
|
const question = (prompt, def = null) => {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
rl.question(`${prompt}${def ? ` (${def})` : ''}: `, answer => {
|
||||||
|
//loop on required
|
||||||
|
if (def === null && !answer) {
|
||||||
|
return resolve(question(prompt, def));
|
||||||
|
}
|
||||||
|
|
||||||
|
return resolve(answer || def);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
//questions
|
||||||
|
(async () => {
|
||||||
|
//project configuration
|
||||||
|
const appName = await question('App Name', 'news');
|
||||||
|
const appWebAddress = await question('Web Addr', `${appName}.example.com`);
|
||||||
|
const appWebOrigin = await question('Web Origin', `https://example.com`); //TODO: clean these up properly
|
||||||
|
const appPort = await question('App Port', '3100');
|
||||||
|
|
||||||
|
//configure the database address
|
||||||
|
let dbLocation = '';
|
||||||
|
while (typeof dbLocation != 'string' || /^[le]/i.test(dbLocation[0]) == false) {
|
||||||
|
dbLocation = await question('[l]ocal or [e]xternal database?');
|
||||||
|
}
|
||||||
|
|
||||||
|
let appDBHost = '';
|
||||||
|
let appDBPort = '';
|
||||||
|
|
||||||
|
if (/^[l]/i.test(dbLocation[0])) {
|
||||||
|
appDBHost = 'database';
|
||||||
|
appDBPort = '3306';
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
appDBHost = await question('DB Host');
|
||||||
|
appDBPort = await question('DB Port', '3306');
|
||||||
|
}
|
||||||
|
|
||||||
|
//configure the database account
|
||||||
|
const appDBUser = await question('DB User', appName);
|
||||||
|
const appDBPass = await question('DB Pass', 'venusaur');
|
||||||
|
const dbRootPass = await question('DB Root Pass');
|
||||||
|
|
||||||
|
const appSecretAccess = await question('Access Token Secret', uuid(32));
|
||||||
|
|
||||||
|
const supportEmail = await question('Support Email', 'example@example.com');
|
||||||
|
|
||||||
|
//generate the files
|
||||||
|
const ymlfile = `
|
||||||
|
services:
|
||||||
|
${appName}:
|
||||||
|
build:
|
||||||
|
context: .
|
||||||
|
ports:
|
||||||
|
- ${appPort}
|
||||||
|
labels:
|
||||||
|
- traefik.enable=true
|
||||||
|
- traefik.http.routers.${appName}router.rule=Host(\`${appWebAddress}\`)
|
||||||
|
- traefik.http.routers.${appName}router.entrypoints=websecure
|
||||||
|
- traefik.http.routers.${appName}router.tls.certresolver=myresolver
|
||||||
|
- traefik.http.routers.${appName}router.service=${appName}service@docker
|
||||||
|
- traefik.http.services.${appName}service.loadbalancer.server.port=${appPort}
|
||||||
|
environment:
|
||||||
|
- WEB_PORT=${appPort}
|
||||||
|
- WEB_ORIGIN=${appWebOrigin}
|
||||||
|
- DB_HOSTNAME=${appDBHost}
|
||||||
|
- DB_PORTNAME=${appDBPort}
|
||||||
|
- DB_DATABASE=${appName}
|
||||||
|
- DB_USERNAME=${appDBUser}
|
||||||
|
- DB_PASSWORD=${appDBPass}
|
||||||
|
- DB_TIMEZONE=Australia/Sydney
|
||||||
|
- PAGE_SIZE=10
|
||||||
|
- SECRET_ACCESS=${appSecretAccess}
|
||||||
|
volumes:
|
||||||
|
- /etc/timezone:/etc/timezone:ro
|
||||||
|
- /etc/localtime:/etc/localtime:ro
|
||||||
|
networks:
|
||||||
|
- app-network${ appDBHost != 'database' ? '' : `
|
||||||
|
depends_on:
|
||||||
|
- database
|
||||||
|
|
||||||
|
database:
|
||||||
|
image: mariadb:latest
|
||||||
|
environment:
|
||||||
|
MYSQL_DATABASE: ${appName}
|
||||||
|
MYSQL_TCP_PORT: ${appDBPort}
|
||||||
|
MYSQL_USER: ${appDBUser}
|
||||||
|
MYSQL_PASSWORD: ${appDBPass}
|
||||||
|
MYSQL_ROOT_PASSWORD: ${dbRootPass}
|
||||||
|
networks:
|
||||||
|
- app-network
|
||||||
|
volumes:
|
||||||
|
- ./mysql:/var/lib/mysql
|
||||||
|
- ./startup.sql:/docker-entrypoint-initdb.d/startup.sql:ro
|
||||||
|
- /etc/timezone:/etc/timezone:ro
|
||||||
|
- /etc/localtime:/etc/localtime:ro`}
|
||||||
|
|
||||||
|
traefik_${appName}:
|
||||||
|
image: traefik:latest
|
||||||
|
command:
|
||||||
|
- --log.level=ERROR
|
||||||
|
- --api.insecure=false
|
||||||
|
- --providers.docker=true
|
||||||
|
- --providers.docker.exposedbydefault=false
|
||||||
|
- --entrypoints.websecure.address=:443
|
||||||
|
- --certificatesresolvers.myresolver.acme.tlschallenge=true
|
||||||
|
- --certificatesresolvers.myresolver.acme.email=${supportEmail}
|
||||||
|
- --certificatesresolvers.myresolver.acme.storage=/letsencrypt/acme.json
|
||||||
|
ports:
|
||||||
|
- 80:80
|
||||||
|
- 443:443
|
||||||
|
volumes:
|
||||||
|
- ./letsencrypt:/letsencrypt
|
||||||
|
- /var/run/docker.sock:/var/run/docker.sock:ro
|
||||||
|
networks:
|
||||||
|
- app-network
|
||||||
|
|
||||||
|
networks:
|
||||||
|
app-network:
|
||||||
|
driver: bridge
|
||||||
|
`;
|
||||||
|
|
||||||
|
const dockerfile = `
|
||||||
|
FROM node:22-bookworm-slim
|
||||||
|
WORKDIR "/app"
|
||||||
|
COPY package*.json /app
|
||||||
|
RUN npm install --omit=dev
|
||||||
|
COPY . /app
|
||||||
|
EXPOSE ${appPort}
|
||||||
|
USER node
|
||||||
|
ENTRYPOINT ["bash", "-c"]
|
||||||
|
CMD ["sleep 10 && npm start"]
|
||||||
|
`;
|
||||||
|
|
||||||
|
const sqlfile = `
|
||||||
|
CREATE DATABASE IF NOT EXISTS ${appName};
|
||||||
|
CREATE USER IF NOT EXISTS '${appDBUser}'@'%' IDENTIFIED BY '${appDBPass}';
|
||||||
|
GRANT ALL PRIVILEGES ON ${appName}.* TO '${appDBUser}'@'%';
|
||||||
|
`;
|
||||||
|
|
||||||
|
fs.writeFileSync('docker-compose.yml', ymlfile);
|
||||||
|
fs.writeFileSync('Dockerfile', dockerfile);
|
||||||
|
fs.writeFileSync('startup.sql', sqlfile);
|
||||||
|
})()
|
||||||
|
.then(() => rl.close())
|
||||||
|
.catch(e => console.error(e))
|
||||||
|
;
|
||||||
@@ -1,38 +0,0 @@
|
|||||||
version: '3'
|
|
||||||
|
|
||||||
services:
|
|
||||||
|
|
||||||
app:
|
|
||||||
build:
|
|
||||||
context: .
|
|
||||||
environment:
|
|
||||||
WEB_PORT: 3100
|
|
||||||
DB_HOSTNAME: database
|
|
||||||
DB_DATABASE: news
|
|
||||||
DB_USERNAME: news
|
|
||||||
DB_PASSWORD: charizard
|
|
||||||
DB_TIMEZONE: Australia/Sydney
|
|
||||||
QUERY_LIMIT: 10
|
|
||||||
QUERY_KEY: key
|
|
||||||
networks:
|
|
||||||
- app-network
|
|
||||||
ports:
|
|
||||||
- "3100:3100"
|
|
||||||
depends_on:
|
|
||||||
- database
|
|
||||||
|
|
||||||
database:
|
|
||||||
image: mariadb:latest
|
|
||||||
environment:
|
|
||||||
MYSQL_DATABASE: news
|
|
||||||
MYSQL_USER: news
|
|
||||||
MYSQL_PASSWORD: charizard
|
|
||||||
MYSQL_ROOT_PASSWORD: root
|
|
||||||
networks:
|
|
||||||
- app-network
|
|
||||||
volumes:
|
|
||||||
- ./data:/var/lib/mysql
|
|
||||||
|
|
||||||
networks:
|
|
||||||
app-network:
|
|
||||||
driver: bridge
|
|
||||||
@@ -1,110 +0,0 @@
|
|||||||
import React, { useState } from 'react';
|
|
||||||
import Select from 'react-dropdown-select';
|
|
||||||
|
|
||||||
//DOCS: props.uri is the address of a live news-server
|
|
||||||
//DOCS: props.newsKey is the key of the live news-server
|
|
||||||
const NewsEditor = props => {
|
|
||||||
let titleElement, authorElement, bodyElement;
|
|
||||||
const [articles, setArticles] = useState(null);
|
|
||||||
const [index, setIndex] = useState(null);
|
|
||||||
|
|
||||||
if (!articles) {
|
|
||||||
fetch(`${props.uri}/titles?limit=999`, { method: 'GET' })
|
|
||||||
.then(a => {
|
|
||||||
if (!a.ok) {
|
|
||||||
throw `Network error ${a.status}: ${a.statusText} ${a.url}`;
|
|
||||||
}
|
|
||||||
return a.json();
|
|
||||||
})
|
|
||||||
.then(a => setArticles(a))
|
|
||||||
.catch(e => console.error(e))
|
|
||||||
;
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div>
|
|
||||||
<h2 className='centered'>News Editor</h2>
|
|
||||||
<div>
|
|
||||||
<label htmlFor='article'>Article: </label>
|
|
||||||
<Select
|
|
||||||
options={(articles || []).map(article => { return { label: article.title, value: article.index }; })}
|
|
||||||
onChange={values => setIndex(fetchSelection(values[0].value, titleElement, authorElement, bodyElement, props.uri))}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<form onSubmit={async e => {
|
|
||||||
e.preventDefault();
|
|
||||||
await handleSubmit(index, titleElement.value, authorElement.value, bodyElement.value, props.uri, props.newsKey);
|
|
||||||
titleElement.value = authorElement.value = bodyElement.value = '';
|
|
||||||
}}>
|
|
||||||
<div>
|
|
||||||
<label htmlFor='title'>Title: </label>
|
|
||||||
<input type='text' name='title' ref={ e => titleElement = e } />
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div>
|
|
||||||
<label htmlFor='author'>Author: </label>
|
|
||||||
<input type='text' name='author' ref={ e => authorElement = e } />
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div>
|
|
||||||
<label htmlFor='body'>Body: </label>
|
|
||||||
<textarea name='body' rows='10' cols='150' ref={ e => bodyElement = e } />
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<button type='submit'>Update</button>
|
|
||||||
</form>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
const fetchSelection = (index, titleElement, authorElement, bodyElement, uri) => {
|
|
||||||
fetch(`${uri}/archive/${index}`, {
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
'Access-Control-Allow-Origin': '*'
|
|
||||||
})
|
|
||||||
.then(blob => blob.json())
|
|
||||||
.then(article => {
|
|
||||||
titleElement.value = article.title;
|
|
||||||
authorElement.value = article.author;
|
|
||||||
bodyElement.value = article.body;
|
|
||||||
})
|
|
||||||
.catch(e => console.error(e))
|
|
||||||
;
|
|
||||||
|
|
||||||
return index; //this is admittedly odd
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleSubmit = async (index, title, author, body, uri, newsKey) => {
|
|
||||||
title = title.trim();
|
|
||||||
author = author.trim();
|
|
||||||
body = body.trim();
|
|
||||||
uri = uri.trim();
|
|
||||||
newsKey = newsKey.trim();
|
|
||||||
|
|
||||||
//fetch POST json data
|
|
||||||
const raw = await fetch(
|
|
||||||
`${uri}/${index}`,
|
|
||||||
{
|
|
||||||
method: 'PATCH',
|
|
||||||
headers: {
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
'Access-Control-Allow-Origin': '*'
|
|
||||||
},
|
|
||||||
body: JSON.stringify({ title: title, author: author, body: body, key: newsKey })
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
if (raw.ok) {
|
|
||||||
const result = await raw.json();
|
|
||||||
|
|
||||||
if (result.ok) {
|
|
||||||
alert(`Updated article index ${index}`);
|
|
||||||
} else {
|
|
||||||
alert(result.error);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
alert(raw.statusText);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
export default NewsEditor;
|
|
||||||
@@ -1,42 +0,0 @@
|
|||||||
import React, { useState } from 'react';
|
|
||||||
import dateFormat from 'dateformat';
|
|
||||||
|
|
||||||
//DOCS: props.uri is the address of a live news-server
|
|
||||||
const NewsFeed = props => {
|
|
||||||
const [articles, setArticles] = useState(null);
|
|
||||||
|
|
||||||
if (!articles) {
|
|
||||||
fetch(props.uri, { method: 'GET' })
|
|
||||||
.then(a => {
|
|
||||||
if (!a.ok) {
|
|
||||||
throw `Network error ${a.status}: ${a.statusText} ${a.url}`;
|
|
||||||
}
|
|
||||||
return a.json();
|
|
||||||
})
|
|
||||||
.then(a => setArticles(a))
|
|
||||||
.catch(e => console.error(e))
|
|
||||||
;
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div>
|
|
||||||
<h1 className='centered'>News Feed</h1>
|
|
||||||
{(articles || []).map((article, index) => {
|
|
||||||
return (
|
|
||||||
<div key={index}>
|
|
||||||
<hr />
|
|
||||||
<h2>{article.title}</h2>
|
|
||||||
<p>Written by <strong>{article.author}</strong>, {
|
|
||||||
article.edits > 0 ?
|
|
||||||
<span>Last Updated {dateFormat(articles.updatedAt, 'fullDate')} ({`${article.edits} edit${article.edits > 1 ? 's': ''}`})</span> :
|
|
||||||
<span>Published {dateFormat(articles.createdAt, 'fullDate')}</span>
|
|
||||||
}</p>
|
|
||||||
<p style={{whiteSpace: 'pre-wrap'}}>{article.body}</p>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
export default NewsFeed;
|
|
||||||
@@ -1,70 +0,0 @@
|
|||||||
import React from 'react';
|
|
||||||
|
|
||||||
//DOCS: props.uri is the address of a live news-server
|
|
||||||
//DOCS: props.newsKey is the key of the live news-server
|
|
||||||
const NewsPublisher = props => {
|
|
||||||
let titleElement, authorElement, bodyElement;
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div>
|
|
||||||
<h2 className='centered'>News Publisher</h2>
|
|
||||||
<form onSubmit={async e => {
|
|
||||||
e.preventDefault();
|
|
||||||
await handleSubmit(titleElement.value, authorElement.value, bodyElement.value, props.uri, props.newsKey);
|
|
||||||
titleElement.value = authorElement.value = bodyElement.value = '';
|
|
||||||
}}>
|
|
||||||
<div>
|
|
||||||
<label htmlFor='title'>Title: </label>
|
|
||||||
<input type='text' name='title' ref={ e => titleElement = e } />
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div>
|
|
||||||
<label htmlFor='author'>Author: </label>
|
|
||||||
<input type='text' name='author' ref={ e => authorElement = e } />
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div>
|
|
||||||
<label htmlFor='body'>Body: </label>
|
|
||||||
<textarea name='body' rows='10' cols='150' ref={ e => bodyElement = e } />
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<button type='submit'>Publish</button>
|
|
||||||
</form>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleSubmit = async (title, author, body, uri, newsKey) => {
|
|
||||||
title = title.trim();
|
|
||||||
author = author.trim();
|
|
||||||
body = body.trim();
|
|
||||||
uri = uri.trim();
|
|
||||||
newsKey = newsKey.trim();
|
|
||||||
|
|
||||||
//fetch POST json data
|
|
||||||
const raw = await fetch(
|
|
||||||
uri,
|
|
||||||
{
|
|
||||||
method: 'POST',
|
|
||||||
headers: {
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
'Access-Control-Allow-Origin': '*'
|
|
||||||
},
|
|
||||||
body: JSON.stringify({ title: title, author: author, body: body, key: newsKey })
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
if (raw.ok) {
|
|
||||||
const result = await raw.json();
|
|
||||||
|
|
||||||
if (result.ok) {
|
|
||||||
alert(`Published article index ${result.index}`);
|
|
||||||
} else {
|
|
||||||
alert(result.error);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
alert(raw.statusText);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
export default NewsPublisher;
|
|
||||||
Generated
+989
-2923
File diff suppressed because it is too large
Load Diff
+9
-8
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "news-server",
|
"name": "news-server",
|
||||||
"version": "1.0.0",
|
"version": "1.7.5",
|
||||||
"description": "An API centric news server. Uses Sequelize and mariaDB by default.",
|
"description": "An API centric news server. Uses Sequelize and mariaDB by default.",
|
||||||
"main": "server/server.js",
|
"main": "server/server.js",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
@@ -13,20 +13,21 @@
|
|||||||
"url": "git+https://github.com/krgamestudios/news-server.git"
|
"url": "git+https://github.com/krgamestudios/news-server.git"
|
||||||
},
|
},
|
||||||
"author": "Kayne Ruse",
|
"author": "Kayne Ruse",
|
||||||
"license": "ISC",
|
"license": "Zlib",
|
||||||
"bugs": {
|
"bugs": {
|
||||||
"url": "https://github.com/krgamestudios/news-server/issues"
|
"url": "https://github.com/krgamestudios/news-server/issues"
|
||||||
},
|
},
|
||||||
"homepage": "https://github.com/krgamestudios/news-server#readme",
|
"homepage": "https://github.com/krgamestudios/news-server#readme",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"body-parser": "^1.19.0",
|
|
||||||
"cors": "^2.8.5",
|
"cors": "^2.8.5",
|
||||||
"dotenv": "^8.2.0",
|
"dotenv": "^17.2.3",
|
||||||
"express": "^4.17.1",
|
"express": "^5.2.1",
|
||||||
"mariadb": "^2.5.2",
|
"jsonwebtoken": "^9.0.3",
|
||||||
"sequelize": "^6.5.0"
|
"mariadb": "^3.4.5",
|
||||||
|
"markdown-it": "^14.1.0",
|
||||||
|
"sequelize": "^6.37.7"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"nodemon": "^2.0.7"
|
"nodemon": "^3.1.11"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,11 +2,10 @@ const Sequelize = require('sequelize');
|
|||||||
|
|
||||||
const sequelize = new Sequelize(process.env.DB_DATABASE, process.env.DB_USERNAME, process.env.DB_PASSWORD, {
|
const sequelize = new Sequelize(process.env.DB_DATABASE, process.env.DB_USERNAME, process.env.DB_PASSWORD, {
|
||||||
host: process.env.DB_HOSTNAME,
|
host: process.env.DB_HOSTNAME,
|
||||||
|
port: process.env.DB_PORTNAME,
|
||||||
dialect: 'mariadb',
|
dialect: 'mariadb',
|
||||||
timezone: process.env.DB_TIMEZONE,
|
timezone: process.env.DB_TIMEZONE,
|
||||||
logging: false
|
logging: process.env.DB_LOGGING ? console.log : false
|
||||||
});
|
});
|
||||||
|
|
||||||
sequelize.sync();
|
|
||||||
|
|
||||||
module.exports = sequelize;
|
module.exports = sequelize;
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
const Sequelize = require('sequelize');
|
const Sequelize = require('sequelize');
|
||||||
const sequelize = require('..');
|
const sequelize = require('..');
|
||||||
|
|
||||||
module.exports = sequelize.define('articles', {
|
const articles = sequelize.define('articles', {
|
||||||
index: {
|
index: {
|
||||||
type: Sequelize.INTEGER(11),
|
type: Sequelize.INTEGER(11),
|
||||||
allowNull: false,
|
allowNull: false,
|
||||||
@@ -25,8 +25,17 @@ module.exports = sequelize.define('articles', {
|
|||||||
defaultValue: ''
|
defaultValue: ''
|
||||||
},
|
},
|
||||||
|
|
||||||
|
rendered: {
|
||||||
|
type: Sequelize.TEXT,
|
||||||
|
defaultValue: ''
|
||||||
|
},
|
||||||
|
|
||||||
edits: {
|
edits: {
|
||||||
type: Sequelize.INTEGER(11),
|
type: Sequelize.INTEGER(11),
|
||||||
defaultValue: 0
|
defaultValue: 0
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
sequelize.sync();
|
||||||
|
|
||||||
|
module.exports = articles;
|
||||||
@@ -1,9 +1,15 @@
|
|||||||
const Sequelize = require('sequelize');
|
const Sequelize = require('sequelize');
|
||||||
const sequelize = require('..');
|
const sequelize = require('..');
|
||||||
|
|
||||||
const articles = require('./articles');
|
|
||||||
|
|
||||||
const revisions = sequelize.define('revisions', {
|
const revisions = sequelize.define('revisions', {
|
||||||
|
index: {
|
||||||
|
type: Sequelize.INTEGER(11),
|
||||||
|
allowNull: false,
|
||||||
|
autoIncrement: true,
|
||||||
|
primaryKey: true,
|
||||||
|
unique: true
|
||||||
|
},
|
||||||
|
|
||||||
title: {
|
title: {
|
||||||
type: Sequelize.TEXT,
|
type: Sequelize.TEXT,
|
||||||
defaultValue: ''
|
defaultValue: ''
|
||||||
@@ -17,12 +23,20 @@ const revisions = sequelize.define('revisions', {
|
|||||||
body: {
|
body: {
|
||||||
type: Sequelize.TEXT,
|
type: Sequelize.TEXT,
|
||||||
defaultValue: ''
|
defaultValue: ''
|
||||||
|
},
|
||||||
|
|
||||||
|
rendered: {
|
||||||
|
type: Sequelize.TEXT,
|
||||||
|
defaultValue: ''
|
||||||
|
},
|
||||||
|
|
||||||
|
originalIndex: {
|
||||||
|
type: Sequelize.INTEGER(11),
|
||||||
|
default: null
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
//relationships
|
//relationships
|
||||||
articles.hasOne(revisions, { as: 'original' });
|
|
||||||
|
|
||||||
sequelize.sync();
|
sequelize.sync();
|
||||||
|
|
||||||
module.exports = revisions;
|
module.exports = revisions;
|
||||||
+8
-12
@@ -1,12 +1,8 @@
|
|||||||
const { Op } = require('sequelize');
|
const { Op } = require('sequelize');
|
||||||
const { articles, revisions } = require('../database/models');
|
const { articles, revisions } = require('../database/models');
|
||||||
|
const markdownIt = require('markdown-it')({ html: true });
|
||||||
|
|
||||||
const route = async (req, res) => {
|
const route = async (req, res) => {
|
||||||
//check the key
|
|
||||||
if (req.body.key != process.env.QUERY_KEY) {
|
|
||||||
return res.status(401).json({ ok: false, error: 'invalid key' });
|
|
||||||
}
|
|
||||||
|
|
||||||
//get the existing record
|
//get the existing record
|
||||||
const record = await articles.findOne({
|
const record = await articles.findOne({
|
||||||
where: {
|
where: {
|
||||||
@@ -17,7 +13,7 @@ const route = async (req, res) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
if (!record) {
|
if (!record) {
|
||||||
return res.status(500).json({ ok: false, error: 'failed to update non-existing record' });
|
return res.status(500).send('Failed to update non-existing record');
|
||||||
}
|
}
|
||||||
|
|
||||||
//store the revision
|
//store the revision
|
||||||
@@ -25,14 +21,16 @@ const route = async (req, res) => {
|
|||||||
title: record.title,
|
title: record.title,
|
||||||
author: record.author,
|
author: record.author,
|
||||||
body: record.body,
|
body: record.body,
|
||||||
|
rendered: record.rendered,
|
||||||
originalIndex: record.index
|
originalIndex: record.index
|
||||||
});
|
});
|
||||||
|
|
||||||
//update the data
|
//update the data
|
||||||
await articles.update({
|
await articles.update({
|
||||||
title: req.body.title,
|
title: req.body.title || record.title,
|
||||||
author: req.body.author,
|
author: req.body.author || record.author,
|
||||||
body: req.body.body,
|
body: req.body.body || record.body,
|
||||||
|
rendered: markdownIt.render(req.body.body) || record.rendered,
|
||||||
edits: record.edits + 1
|
edits: record.edits + 1
|
||||||
}, {
|
}, {
|
||||||
where: {
|
where: {
|
||||||
@@ -40,9 +38,7 @@ const route = async (req, res) => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
return res.status(200).json({
|
return res.status(200).end();
|
||||||
ok: true
|
|
||||||
});
|
|
||||||
};
|
};
|
||||||
|
|
||||||
module.exports = route;
|
module.exports = route;
|
||||||
+30
-13
@@ -1,5 +1,9 @@
|
|||||||
const express = require('express');
|
const express = require('express');
|
||||||
const router = express.Router();
|
const router = express.Router();
|
||||||
|
const cors = require('cors'); //route-by-route, because some routes are available without authentication
|
||||||
|
|
||||||
|
//middleware
|
||||||
|
const authToken = require('../utilities/token-auth');
|
||||||
|
|
||||||
//the routes
|
//the routes
|
||||||
const query = require('./query');
|
const query = require('./query');
|
||||||
@@ -7,20 +11,33 @@ const publish = require('./publish');
|
|||||||
const edit = require('./edit');
|
const edit = require('./edit');
|
||||||
const remove = require('./remove');
|
const remove = require('./remove');
|
||||||
|
|
||||||
//basic route management
|
//basic route management (all query possibilities)
|
||||||
router.get('/', query(false, false));
|
router.get('/{:id}', cors(), query(false, false));
|
||||||
router.get('/:id(\\d+)', query(false, false));
|
router.get('/archive/{:id}', cors(), query(true, false));
|
||||||
router.get('/archive', query(true, false));
|
router.get('/metadata/{:id}', cors(), query(false, true));
|
||||||
router.get('/archive/:id(\\d+)', query(true, false));
|
router.get('/archive/metadata/{:id}', cors(), query(true, true));
|
||||||
router.get('/titles', query(false, true));
|
|
||||||
router.get('/titles/:id(\\d+)', query(false, true));
|
|
||||||
router.get('/archive/titles', query(true, true));
|
|
||||||
router.get('/archive/titles/:id(\\d+)', query(true, true));
|
|
||||||
|
|
||||||
|
//use middleware to authenticate the rest of the routes
|
||||||
|
router.use(cors({
|
||||||
|
credentials: true,
|
||||||
|
origin: [`${process.env.WEB_ORIGIN}`], //because auth-server
|
||||||
|
allowedHeaders: ['Origin', 'X-Requested-With', 'Content-Type', 'Accept', 'Authorization', 'Set-Cookie'],
|
||||||
|
exposedHeaders: ['Origin', 'X-Requested-With', 'Content-Type', 'Accept', 'Authorization', 'Set-Cookie'],
|
||||||
|
}));
|
||||||
|
|
||||||
|
router.use(authToken);
|
||||||
|
|
||||||
|
router.use((req, res, next) => {
|
||||||
|
if (req.user.mod) {
|
||||||
|
next();
|
||||||
|
} else {
|
||||||
|
res.status(403).end();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
//authenticated routes
|
||||||
router.post('/', publish);
|
router.post('/', publish);
|
||||||
|
router.patch('/{:id}', edit);
|
||||||
router.patch('/:id(\\d+)', edit);
|
router.delete('/{:id}', remove);
|
||||||
|
|
||||||
router.delete('/:id(\\d+)', remove);
|
|
||||||
|
|
||||||
module.exports = router;
|
module.exports = router;
|
||||||
|
|||||||
+16
-7
@@ -1,23 +1,33 @@
|
|||||||
const { articles } = require('../database/models');
|
const { articles } = require('../database/models');
|
||||||
|
const markdownIt = require('markdown-it')({ html: true });
|
||||||
|
|
||||||
const route = async (req, res) => {
|
const route = async (req, res) => {
|
||||||
//check the key
|
//check for missing data
|
||||||
if (req.body.key != process.env.QUERY_KEY) {
|
if (!req.body.title) {
|
||||||
return res.status(401).json({ ok: false, error: 'invalid key' });
|
return res.status(401).end("Missing title");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!req.body.author) {
|
||||||
|
return res.status(401).end("Missing author");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!req.body.body) {
|
||||||
|
return res.status(401).end("Missing body");
|
||||||
}
|
}
|
||||||
|
|
||||||
//upsert the data
|
//upsert the data
|
||||||
const [instance, created] = await articles.upsert({
|
const [instance, created] = await articles.upsert({
|
||||||
title: req.body.title,
|
title: req.body.title,
|
||||||
author: req.body.author,
|
author: req.body.author,
|
||||||
body: req.body.body
|
body: req.body.body,
|
||||||
|
rendered: markdownIt.render(req.body.body),
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!created) {
|
if (!created) {
|
||||||
return res.status(500).json({ ok: false, error: 'failed to create record' });
|
return res.status(500).send('Failed to create record');
|
||||||
}
|
}
|
||||||
|
|
||||||
//BUGFIX
|
//BUGFIX: instance doesn't have the index for some reason
|
||||||
const result = await articles.findOne({
|
const result = await articles.findOne({
|
||||||
order: [
|
order: [
|
||||||
['index', 'DESC']
|
['index', 'DESC']
|
||||||
@@ -25,7 +35,6 @@ const route = async (req, res) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
return res.status(200).json({
|
return res.status(200).json({
|
||||||
ok: true,
|
|
||||||
// index: instance.get('index')
|
// index: instance.get('index')
|
||||||
index: result.index
|
index: result.index
|
||||||
});
|
});
|
||||||
|
|||||||
+45
-18
@@ -1,38 +1,65 @@
|
|||||||
const { Op } = require('sequelize');
|
|
||||||
const { articles } = require('../database/models');
|
const { articles } = require('../database/models');
|
||||||
|
|
||||||
//the query function that can be reused
|
//the query function that can be reused
|
||||||
const query = (ascending, titlesOnly) => async (req, res) => {
|
const query = (ascending, metadataOnly) => async (req, res) => {
|
||||||
//specific search
|
if (process.env.QUERY_LIMIT) {
|
||||||
if (req.params.id && typeof(parseInt(req.params.id)) === 'number') {
|
process.env.PAGE_SIZE = process.env.QUERY_LIMIT;
|
||||||
|
console.warn('The use of QUERY_LIMIT is deprecated. Please use PAGE_SIZE instead.');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (req.query.limit) {
|
||||||
|
req.query.page_size = req.query.limit;
|
||||||
|
console.warn('The use of the limit parameter is deprecated. Please use page_size instead.');
|
||||||
|
}
|
||||||
|
|
||||||
|
const PAGE_SIZE = parseInt(req.query.page_size) || parseInt(process.env.PAGE_SIZE) || 999;
|
||||||
|
const PAGE = parseInt(req.query.page) || 1;
|
||||||
|
const ARTICLE_ID = req.params.id ? parseInt(req.params.id) : undefined;
|
||||||
|
const FIELDS = req.query.fields ? req.query.fields.split(',') : undefined;
|
||||||
|
|
||||||
|
const attributes = [
|
||||||
|
'index',
|
||||||
|
'author',
|
||||||
|
'createdAt',
|
||||||
|
'edits',
|
||||||
|
'title',
|
||||||
|
'updatedAt',
|
||||||
|
].concat(metadataOnly ? [] : [
|
||||||
|
'body',
|
||||||
|
'rendered'
|
||||||
|
]);
|
||||||
|
|
||||||
|
//filter out attributes that aren't requested
|
||||||
|
const attributesToFetch = FIELDS ? attributes.filter((attr) => {
|
||||||
|
return FIELDS.includes(attr) || attr === 'index';
|
||||||
|
}) : attributes;
|
||||||
|
|
||||||
|
//specific search (id is defined)
|
||||||
|
if (typeof(ARTICLE_ID) === 'number' && !isNaN(ARTICLE_ID)) {
|
||||||
const result = await articles.findOne({
|
const result = await articles.findOne({
|
||||||
attributes: [
|
attributes: attributesToFetch,
|
||||||
'index', 'title', 'author', 'edits', 'createdAt', 'updatedAt', ...(!titlesOnly ? ['body'] : [])
|
|
||||||
],
|
|
||||||
where: {
|
where: {
|
||||||
index: {
|
index: ascending ? ARTICLE_ID : (await articles.max('index') - ARTICLE_ID) + 1,
|
||||||
[Op.eq]: ascending ? parseInt(req.params.id) : (await articles.max('index')) - parseInt(req.params.id) + 1
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
//returns null if failed to find
|
//result is null if failed to find
|
||||||
return res.status(200).json(result);
|
return res.status(200).json(result || []);
|
||||||
}
|
}
|
||||||
|
|
||||||
//default search
|
//default search
|
||||||
else {
|
else {
|
||||||
const result = await articles.findAndCountAll({
|
const result = await articles.findAndCountAll({
|
||||||
attributes: [
|
attributes: attributesToFetch,
|
||||||
'index', 'title', 'author', 'edits', 'createdAt', 'updatedAt', ...(!titlesOnly ? ['body'] : [])
|
limit: PAGE_SIZE,
|
||||||
],
|
offset: Math.max((PAGE - 1) * PAGE_SIZE, 0),
|
||||||
order: [
|
order: [
|
||||||
['index', ascending ? 'ASC' : 'DESC']
|
['index', ascending ? 'ASC' : 'DESC']
|
||||||
],
|
]
|
||||||
limit: parseInt(req.query.limit) || parseInt(process.env.QUERY_LIMIT) || 999
|
|
||||||
});
|
});
|
||||||
|
|
||||||
return res.status(200).json(result.rows || result);
|
//result is empty array if failed to find
|
||||||
|
return res.status(200).json(result.rows || result || []);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -2,11 +2,6 @@ const { Op } = require('sequelize');
|
|||||||
const { articles, revisions } = require('../database/models');
|
const { articles, revisions } = require('../database/models');
|
||||||
|
|
||||||
const route = async (req, res) => {
|
const route = async (req, res) => {
|
||||||
//check the key
|
|
||||||
if (req.body.key != process.env.QUERY_KEY) {
|
|
||||||
return res.status(401).json({ ok: false, error: 'invalid key' });
|
|
||||||
}
|
|
||||||
|
|
||||||
//get the existing record
|
//get the existing record
|
||||||
const record = await articles.findOne({
|
const record = await articles.findOne({
|
||||||
where: {
|
where: {
|
||||||
@@ -17,7 +12,7 @@ const route = async (req, res) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
if (!record) {
|
if (!record) {
|
||||||
return res.status(500).json({ ok: false, error: 'failed to remove non-existing record' });
|
return res.status(500).json('Failed to remove non-existing record');
|
||||||
}
|
}
|
||||||
|
|
||||||
//store the revision
|
//store the revision
|
||||||
@@ -25,6 +20,7 @@ const route = async (req, res) => {
|
|||||||
title: record.title,
|
title: record.title,
|
||||||
author: record.author,
|
author: record.author,
|
||||||
body: record.body,
|
body: record.body,
|
||||||
|
rendered: record.rendered,
|
||||||
originalIndex: record.index
|
originalIndex: record.index
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -35,9 +31,7 @@ const route = async (req, res) => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
return res.status(200).json({
|
return res.status(200).end();
|
||||||
ok: true
|
|
||||||
});
|
|
||||||
};
|
};
|
||||||
|
|
||||||
module.exports = route;
|
module.exports = route;
|
||||||
+5
-6
@@ -5,12 +5,9 @@ require('dotenv').config();
|
|||||||
const express = require('express');
|
const express = require('express');
|
||||||
const app = express();
|
const app = express();
|
||||||
const server = require('http').Server(app);
|
const server = require('http').Server(app);
|
||||||
const bodyParser = require('body-parser');
|
|
||||||
const cors = require('cors');
|
|
||||||
|
|
||||||
//config
|
//config
|
||||||
app.use(bodyParser.json());
|
app.use(express.json());
|
||||||
app.use(cors());
|
|
||||||
|
|
||||||
//database connection
|
//database connection
|
||||||
const database = require('./database');
|
const database = require('./database');
|
||||||
@@ -19,11 +16,13 @@ const database = require('./database');
|
|||||||
app.use('/news', require('./news'));
|
app.use('/news', require('./news'));
|
||||||
|
|
||||||
//error on access
|
//error on access
|
||||||
app.get('*', (req, res) => {
|
app.get('/{*any}', (req, res) => {
|
||||||
res.redirect('https://github.com/krgamestudios/news-server');
|
res.redirect('https://github.com/krgamestudios/news-server');
|
||||||
});
|
});
|
||||||
|
|
||||||
//startup
|
//startup
|
||||||
server.listen(process.env.WEB_PORT || 3100, (err) => {
|
server.listen(process.env.WEB_PORT || 3100, async (err) => {
|
||||||
|
await database.sync();
|
||||||
console.log(`listening to localhost:${process.env.WEB_PORT || 3100}`);
|
console.log(`listening to localhost:${process.env.WEB_PORT || 3100}`);
|
||||||
|
console.log(`database located at ${process.env.DB_HOSTNAME || '<default>'}:${process.env.DB_PORTNAME || '<default>'}`);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,21 @@
|
|||||||
|
const jwt = require('jsonwebtoken');
|
||||||
|
|
||||||
|
//middleware to authenticate the JWT token
|
||||||
|
module.exports = (req, res, next) => {
|
||||||
|
const authHeader = req.headers['authorization'];
|
||||||
|
const token = authHeader?.split (' ')[1]; //'Bearer token'
|
||||||
|
|
||||||
|
if (!token) {
|
||||||
|
return res.status(401).end();
|
||||||
|
}
|
||||||
|
|
||||||
|
jwt.verify(token, process.env.SECRET_ACCESS, (err, user) => {
|
||||||
|
if (err) {
|
||||||
|
return res.status(403).end();
|
||||||
|
}
|
||||||
|
|
||||||
|
req.user = user;
|
||||||
|
|
||||||
|
next();
|
||||||
|
});
|
||||||
|
};
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
#Query
|
||||||
|
GET https://dev-news.krgamestudios.com/news HTTP/1.1
|
||||||
|
|
||||||
|
###
|
||||||
|
|
||||||
|
#Login
|
||||||
|
POST https://dev-auth.krgamestudios.com/auth/login HTTP/1.1
|
||||||
|
Content-Type: application/json
|
||||||
|
|
||||||
|
{
|
||||||
|
"email": "example@example.com",
|
||||||
|
"password": "helloworld"
|
||||||
|
}
|
||||||
|
|
||||||
|
###
|
||||||
|
|
||||||
|
#Publish
|
||||||
|
POST https://dev-news.krgamestudios.com/news HTTP/1.1
|
||||||
|
Content-Type: application/json
|
||||||
|
Authorization: Bearer
|
||||||
|
|
||||||
|
{
|
||||||
|
"title": "Hello World",
|
||||||
|
"author": "Anonymous",
|
||||||
|
"body": "Lorem ipsum."
|
||||||
|
}
|
||||||
|
|
||||||
|
###
|
||||||
|
|
||||||
|
#Edit
|
||||||
|
PATCH https://dev-news.krgamestudios.com/news/1 HTTP/1.1
|
||||||
|
Content-Type: application/json
|
||||||
|
Authorization: Bearer
|
||||||
|
|
||||||
|
{
|
||||||
|
"title": "Goodnight World"
|
||||||
|
}
|
||||||
|
|
||||||
|
###
|
||||||
|
|
||||||
|
#Delete
|
||||||
|
DELETE https://dev-news.krgamestudios.com/news/1 HTTP/1.1
|
||||||
|
Content-Type: application/json
|
||||||
|
Authorization: Bearer
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
#Query
|
||||||
|
GET http://localhost:3100/news HTTP/1.1
|
||||||
|
|
||||||
|
###
|
||||||
|
|
||||||
|
#Login
|
||||||
|
POST https://dev-auth.krgamestudios.com/auth/login HTTP/1.1
|
||||||
|
Content-Type: application/json
|
||||||
|
|
||||||
|
{
|
||||||
|
"email": "example@example.com",
|
||||||
|
"password": "helloworld"
|
||||||
|
}
|
||||||
|
|
||||||
|
###
|
||||||
|
|
||||||
|
#Publish
|
||||||
|
POST http://localhost:3100/news HTTP/1.1
|
||||||
|
Content-Type: application/json
|
||||||
|
Authorization: Bearer
|
||||||
|
|
||||||
|
{
|
||||||
|
"title": "Hello World",
|
||||||
|
"author": "Anonymous",
|
||||||
|
"body": "Lorem ipsum."
|
||||||
|
}
|
||||||
|
|
||||||
|
###
|
||||||
|
|
||||||
|
#Edit
|
||||||
|
PATCH http://localhost:3100/news/1 HTTP/1.1
|
||||||
|
Content-Type: application/json
|
||||||
|
Authorization: Bearer
|
||||||
|
|
||||||
|
{
|
||||||
|
"title": "Goodnight World"
|
||||||
|
}
|
||||||
|
|
||||||
|
###
|
||||||
|
|
||||||
|
#Delete
|
||||||
|
DELETE http://localhost:3100/news/1 HTTP/1.1
|
||||||
|
Content-Type: application/json
|
||||||
|
Authorization: Bearer
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
#use this while debugging
|
||||||
|
CREATE DATABASE news;
|
||||||
|
CREATE USER 'news'@'%' IDENTIFIED BY 'venusaur';
|
||||||
|
GRANT ALL PRIVILEGES ON news.* TO 'news'@'%';
|
||||||
Reference in New Issue
Block a user