Compare commits
44 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 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 |
@@ -1,6 +1,10 @@
|
||||
WEB_PORT=3100
|
||||
|
||||
DB_HOSTNAME=database
|
||||
WEB_ORIGIN=http://localhost:3001
|
||||
|
||||
DB_HOSTNAME=localhost
|
||||
DB_PORTNAME=3306
|
||||
|
||||
DB_DATABASE=news
|
||||
DB_USERNAME=news
|
||||
DB_PASSWORD=venusaur
|
||||
@@ -15,4 +19,4 @@ DB_LOGGING=
|
||||
SECRET_ACCESS=access
|
||||
|
||||
# Select the default number of articles returned by a GET request
|
||||
QUERY_LIMIT=10
|
||||
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"]
|
||||
@@ -26,7 +26,7 @@ jobs:
|
||||
docker_image: krgamestudios/news-server
|
||||
|
||||
- name: Login to DockerHub
|
||||
uses: docker/login-action@v1
|
||||
uses: docker/login-action@v1
|
||||
with:
|
||||
username: ${{ secrets.DOCKER_USERNAME }}
|
||||
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||
|
||||
+3
-3
@@ -1,9 +1,9 @@
|
||||
|
||||
FROM node:15
|
||||
FROM node:22-bookworm-slim
|
||||
WORKDIR "/app"
|
||||
COPY package*.json ./
|
||||
COPY . /app
|
||||
COPY package*.json /app
|
||||
RUN npm install --production
|
||||
COPY . /app
|
||||
EXPOSE 3100
|
||||
USER node
|
||||
ENTRYPOINT ["bash", "-c"]
|
||||
|
||||
@@ -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.
|
||||
|
||||
|
||||
@@ -2,100 +2,268 @@
|
||||
|
||||
An API centric news server. Uses Sequelize and mariaDB by default.
|
||||
|
||||
This server is available via docker hub at krgamestudios/news-server.
|
||||
|
||||
# Setup
|
||||
|
||||
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.
|
||||
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 10 minutes):
|
||||
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.eggtrainer.com/auth/login HTTP/1.1
|
||||
POST https://dev-auth.krgamestudios.com/auth/login HTTP/1.1
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"email": "kayneruse@gmail.com",
|
||||
"email": "example@example.com",
|
||||
"password": "helloworld"
|
||||
}
|
||||
```
|
||||
|
||||
# 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 an empty array 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"
|
||||
GET /news/:id
|
||||
#### Available Query Parameters
|
||||
|
||||
//get the news starting from the beginning, up to a default limit, or specify the index "id"
|
||||
GET /news/archive/:id
|
||||
- `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
|
||||
|
||||
//result (if only a single article is specified, returns just that article 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
|
||||
},
|
||||
...
|
||||
]
|
||||
> **NOTE**
|
||||
> If a specific article is requested, then just that article is returned rather than an array
|
||||
|
||||
//get the latest metadata, up to a default limit, or specify the index "id"
|
||||
GET /news/metadata/:id
|
||||
### `GET /news/archive/:id?`
|
||||
|
||||
//get the metadata starting from the beginning, up to a default limit, or specify the index "id"
|
||||
GET /news/archive/metadata/:id
|
||||
Get either an array of articles (oldest first), or a specified article if the optional "id" parameter is given.
|
||||
|
||||
//result (if only a single article is specified, returns just that article rather than an array):
|
||||
[
|
||||
{
|
||||
"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
|
||||
},
|
||||
...
|
||||
]
|
||||
#### Response Body
|
||||
|
||||
//send a formatted JSON object, returns new index on success, or error on failure
|
||||
POST /news
|
||||
Authorization: Bearer XXX
|
||||
```jsonc
|
||||
[{
|
||||
// [Number] index of the article
|
||||
"index": index,
|
||||
|
||||
//arguments:
|
||||
{
|
||||
"title": title //title of the article
|
||||
"author": author //author of the article
|
||||
"body": body //body of the article
|
||||
}
|
||||
// [String] author of the article
|
||||
"author": author,
|
||||
|
||||
//result (status 200 on success, otherwise an error status):
|
||||
{
|
||||
"index": index //new index of the article
|
||||
}
|
||||
// [String] raw body of the article
|
||||
"body": body,
|
||||
|
||||
//similar to `POST /news`, but allows overwriting an existing article
|
||||
PATCH /news/:id
|
||||
Authorization: Bearer XXX
|
||||
// [Number] number of times this article has been edited
|
||||
"edits": edits,
|
||||
|
||||
//arguments:
|
||||
{
|
||||
"title": title //title of the article, optional
|
||||
"author": author //author of the article, optional
|
||||
"body": body //body of the article, optional
|
||||
}
|
||||
// [String] body of the article rendered as HTML
|
||||
"rendered": rendered,
|
||||
|
||||
result: status 200 on success, otherwise an error status
|
||||
// [String] title of the article
|
||||
"title": title,
|
||||
|
||||
//remove an article from the news feed
|
||||
DELETE /news/:id
|
||||
Authorization: Bearer XXX
|
||||
// [Date] time article was created
|
||||
"createdAt": createdAt,
|
||||
|
||||
//result: status 200 on success, otherwise an error status
|
||||
// [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
|
||||
{
|
||||
// [String] OPTIONAL: title of the article
|
||||
"title": title,
|
||||
|
||||
// [String] OPTIONAL: author of the article
|
||||
"author": author,
|
||||
|
||||
// [String] OPTIONAL: body of the article
|
||||
"body": body,
|
||||
}
|
||||
```
|
||||
|
||||
#### 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.
|
||||
+57
-30
@@ -30,10 +30,30 @@ const question = (prompt, def = null) => {
|
||||
//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', uuid());
|
||||
const appDBPass = await question('DB Pass', 'venusaur');
|
||||
const dbRootPass = await question('DB Root Pass');
|
||||
|
||||
const appSecretAccess = await question('Access Token Secret', uuid(32));
|
||||
@@ -42,38 +62,43 @@ const question = (prompt, def = null) => {
|
||||
|
||||
//generate the files
|
||||
const ymlfile = `
|
||||
version: '3'
|
||||
|
||||
services:
|
||||
${appName}:
|
||||
build:
|
||||
context: .
|
||||
ports:
|
||||
- "${appPort}"
|
||||
- ${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}"
|
||||
- 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}
|
||||
- DB_HOSTNAME=database
|
||||
- WEB_ORIGIN=${appWebOrigin}
|
||||
- DB_HOSTNAME=${appDBHost}
|
||||
- DB_PORTNAME=${appDBPort}
|
||||
- DB_DATABASE=${appName}
|
||||
- DB_USERNAME=${appDBUser}
|
||||
- DB_PASSWORD=${appDBPass}
|
||||
- DB_TIMEZONE=Australia/Sydney
|
||||
- QUERY_LIMIT=10
|
||||
- PAGE_SIZE=10
|
||||
- SECRET_ACCESS=${appSecretAccess}
|
||||
volumes:
|
||||
- /etc/timezone:/etc/timezone:ro
|
||||
- /etc/localtime:/etc/localtime:ro
|
||||
networks:
|
||||
- app-network
|
||||
- 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}
|
||||
@@ -82,36 +107,38 @@ services:
|
||||
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}:
|
||||
container_name: ${appName}_traefik
|
||||
image: "traefik:v2.4"
|
||||
container_name: "traefik"
|
||||
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"
|
||||
- --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"
|
||||
- 80:80
|
||||
- 443:443
|
||||
volumes:
|
||||
- "./letsencrypt:/letsencrypt"
|
||||
- "/var/run/docker.sock:/var/run/docker.sock:ro"
|
||||
- ./letsencrypt:/letsencrypt
|
||||
- /var/run/docker.sock:/var/run/docker.sock:ro
|
||||
networks:
|
||||
- app-network
|
||||
|
||||
networks:
|
||||
app-network:
|
||||
driver: bridge
|
||||
`;
|
||||
|
||||
const dockerfile = `
|
||||
FROM node:15
|
||||
FROM node:22-bookworm-slim
|
||||
WORKDIR "/app"
|
||||
COPY package*.json ./
|
||||
COPY package*.json /app
|
||||
RUN npm install --production
|
||||
COPY . /app
|
||||
EXPOSE ${appPort}
|
||||
|
||||
Generated
+873
-2993
File diff suppressed because it is too large
Load Diff
+9
-8
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "news-server",
|
||||
"version": "1.2.1",
|
||||
"version": "1.7.1",
|
||||
"description": "An API centric news server. Uses Sequelize and mariaDB by default.",
|
||||
"main": "server/server.js",
|
||||
"scripts": {
|
||||
@@ -13,20 +13,21 @@
|
||||
"url": "git+https://github.com/krgamestudios/news-server.git"
|
||||
},
|
||||
"author": "Kayne Ruse",
|
||||
"license": "ISC",
|
||||
"license": "Zlib",
|
||||
"bugs": {
|
||||
"url": "https://github.com/krgamestudios/news-server/issues"
|
||||
},
|
||||
"homepage": "https://github.com/krgamestudios/news-server#readme",
|
||||
"dependencies": {
|
||||
"cors": "^2.8.5",
|
||||
"dotenv": "^8.6.0",
|
||||
"express": "^4.17.1",
|
||||
"jsonwebtoken": "^8.5.1",
|
||||
"mariadb": "^2.5.4",
|
||||
"sequelize": "^6.6.5"
|
||||
"dotenv": "^17.2.1",
|
||||
"express": "^5.1.0",
|
||||
"jsonwebtoken": "^9.0.2",
|
||||
"mariadb": "^3.4.5",
|
||||
"markdown-it": "^14.1.0",
|
||||
"sequelize": "^6.37.7"
|
||||
},
|
||||
"devDependencies": {
|
||||
"nodemon": "^2.0.12"
|
||||
"nodemon": "^3.1.10"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ const Sequelize = require('sequelize');
|
||||
|
||||
const sequelize = new Sequelize(process.env.DB_DATABASE, process.env.DB_USERNAME, process.env.DB_PASSWORD, {
|
||||
host: process.env.DB_HOSTNAME,
|
||||
port: process.env.DB_PORTNAME,
|
||||
dialect: 'mariadb',
|
||||
timezone: process.env.DB_TIMEZONE,
|
||||
logging: process.env.DB_LOGGING ? console.log : false
|
||||
|
||||
@@ -25,6 +25,11 @@ const articles = sequelize.define('articles', {
|
||||
defaultValue: ''
|
||||
},
|
||||
|
||||
rendered: {
|
||||
type: Sequelize.TEXT,
|
||||
defaultValue: ''
|
||||
},
|
||||
|
||||
edits: {
|
||||
type: Sequelize.INTEGER(11),
|
||||
defaultValue: 0
|
||||
|
||||
@@ -1,9 +1,15 @@
|
||||
const Sequelize = require('sequelize');
|
||||
const sequelize = require('..');
|
||||
|
||||
const articles = require('./articles');
|
||||
|
||||
const revisions = sequelize.define('revisions', {
|
||||
index: {
|
||||
type: Sequelize.INTEGER(11),
|
||||
allowNull: false,
|
||||
autoIncrement: true,
|
||||
primaryKey: true,
|
||||
unique: true
|
||||
},
|
||||
|
||||
title: {
|
||||
type: Sequelize.TEXT,
|
||||
defaultValue: ''
|
||||
@@ -17,12 +23,20 @@ const revisions = sequelize.define('revisions', {
|
||||
body: {
|
||||
type: Sequelize.TEXT,
|
||||
defaultValue: ''
|
||||
},
|
||||
|
||||
rendered: {
|
||||
type: Sequelize.TEXT,
|
||||
defaultValue: ''
|
||||
},
|
||||
|
||||
originalIndex: {
|
||||
type: Sequelize.INTEGER(11),
|
||||
default: null
|
||||
}
|
||||
});
|
||||
|
||||
//relationships
|
||||
articles.hasOne(revisions, { as: 'original' });
|
||||
|
||||
sequelize.sync();
|
||||
|
||||
module.exports = revisions;
|
||||
+6
-3
@@ -1,5 +1,6 @@
|
||||
const { Op } = require('sequelize');
|
||||
const { articles, revisions } = require('../database/models');
|
||||
const markdownIt = require('markdown-it')({ html: true });
|
||||
|
||||
const route = async (req, res) => {
|
||||
//get the existing record
|
||||
@@ -20,14 +21,16 @@ const route = async (req, res) => {
|
||||
title: record.title,
|
||||
author: record.author,
|
||||
body: record.body,
|
||||
rendered: record.rendered,
|
||||
originalIndex: record.index
|
||||
});
|
||||
|
||||
//update the data
|
||||
await articles.update({
|
||||
title: req.body.title,
|
||||
author: req.body.author,
|
||||
body: req.body.body,
|
||||
title: req.body.title || record.title,
|
||||
author: req.body.author || record.author,
|
||||
body: req.body.body || record.body,
|
||||
rendered: markdownIt.render(req.body.body) || record.rendered,
|
||||
edits: record.edits + 1
|
||||
}, {
|
||||
where: {
|
||||
|
||||
+16
-11
@@ -1,5 +1,6 @@
|
||||
const express = require('express');
|
||||
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');
|
||||
@@ -11,19 +12,23 @@ const edit = require('./edit');
|
||||
const remove = require('./remove');
|
||||
|
||||
//basic route management (all query possibilities)
|
||||
router.get('/', query(false, false));
|
||||
router.get('/:id(\\d+)', query(false, false));
|
||||
router.get('/archive', query(true, false));
|
||||
router.get('/archive/:id(\\d+)', query(true, false));
|
||||
router.get('/metadata', query(false, true));
|
||||
router.get('/metadata/:id(\\d+)', query(false, true));
|
||||
router.get('/archive/metadata', query(true, true));
|
||||
router.get('/archive/metadata/:id(\\d+)', query(true, true));
|
||||
router.get('/{:id}', cors(), query(false, false));
|
||||
router.get('/archive/{:id}', cors(), query(true, false));
|
||||
router.get('/metadata/{:id}', cors(), query(false, true));
|
||||
router.get('/archive/metadata/{:id}', cors(), 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.admin) {
|
||||
if (req.user.mod) {
|
||||
next();
|
||||
} else {
|
||||
res.status(403).end();
|
||||
@@ -32,7 +37,7 @@ router.use((req, res, next) => {
|
||||
|
||||
//authenticated routes
|
||||
router.post('/', publish);
|
||||
router.patch('/:id(\\d+)', edit);
|
||||
router.delete('/:id(\\d+)', remove);
|
||||
router.patch('/{:id}', edit);
|
||||
router.delete('/{:id}', remove);
|
||||
|
||||
module.exports = router;
|
||||
|
||||
+16
-1
@@ -1,11 +1,26 @@
|
||||
const { articles } = require('../database/models');
|
||||
const markdownIt = require('markdown-it')({ html: true });
|
||||
|
||||
const route = async (req, res) => {
|
||||
//check for missing data
|
||||
if (!req.body.title) {
|
||||
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
|
||||
const [instance, created] = await articles.upsert({
|
||||
title: req.body.title,
|
||||
author: req.body.author,
|
||||
body: req.body.body
|
||||
body: req.body.body,
|
||||
rendered: markdownIt.render(req.body.body),
|
||||
});
|
||||
|
||||
if (!created) {
|
||||
|
||||
+41
-14
@@ -1,18 +1,45 @@
|
||||
const { Op } = require('sequelize');
|
||||
const { articles } = require('../database/models');
|
||||
|
||||
//the query function that can be reused
|
||||
const query = (ascending, metadataOnly) => async (req, res) => {
|
||||
if (process.env.QUERY_LIMIT) {
|
||||
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 (req.params.id && typeof(parseInt(req.params.id)) === 'number') {
|
||||
if (typeof(ARTICLE_ID) === 'number' && !isNaN(ARTICLE_ID)) {
|
||||
const result = await articles.findOne({
|
||||
attributes: [
|
||||
'index', 'title', 'author', 'edits', 'createdAt', 'updatedAt', ...(!metadataOnly ? ['body'] : [])
|
||||
],
|
||||
attributes: attributesToFetch,
|
||||
where: {
|
||||
index: {
|
||||
[Op.eq]: ascending ? parseInt(req.params.id) : (await articles.max('index')) - parseInt(req.params.id) + 1
|
||||
}
|
||||
index: ascending ? ARTICLE_ID : (await articles.max('index') - ARTICLE_ID) + 1,
|
||||
}
|
||||
});
|
||||
|
||||
@@ -23,16 +50,16 @@ const query = (ascending, metadataOnly) => async (req, res) => {
|
||||
//default search
|
||||
else {
|
||||
const result = await articles.findAndCountAll({
|
||||
attributes: [
|
||||
'index', 'title', 'author', 'edits', 'createdAt', 'updatedAt', ...(!metadataOnly ? ['body'] : [])
|
||||
],
|
||||
attributes: attributesToFetch,
|
||||
limit: PAGE_SIZE,
|
||||
offset: Math.max((PAGE - 1) * PAGE_SIZE, 0),
|
||||
order: [
|
||||
['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 || []);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -20,6 +20,7 @@ const route = async (req, res) => {
|
||||
title: record.title,
|
||||
author: record.author,
|
||||
body: record.body,
|
||||
rendered: record.rendered,
|
||||
originalIndex: record.index
|
||||
});
|
||||
|
||||
|
||||
+2
-3
@@ -5,11 +5,9 @@ require('dotenv').config();
|
||||
const express = require('express');
|
||||
const app = express();
|
||||
const server = require('http').Server(app);
|
||||
const cors = require('cors');
|
||||
|
||||
//config
|
||||
app.use(express.json());
|
||||
app.use(cors());
|
||||
|
||||
//database connection
|
||||
const database = require('./database');
|
||||
@@ -18,7 +16,7 @@ const database = require('./database');
|
||||
app.use('/news', require('./news'));
|
||||
|
||||
//error on access
|
||||
app.get('*', (req, res) => {
|
||||
app.get('/{*any}', (req, res) => {
|
||||
res.redirect('https://github.com/krgamestudios/news-server');
|
||||
});
|
||||
|
||||
@@ -26,4 +24,5 @@ app.get('*', (req, res) => {
|
||||
server.listen(process.env.WEB_PORT || 3100, async (err) => {
|
||||
await database.sync();
|
||||
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>'}`);
|
||||
});
|
||||
|
||||
@@ -1,23 +1,34 @@
|
||||
#Query
|
||||
GET https://dev-news.eggtrainer.com/news HTTP/1.1
|
||||
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.eggtrainer.com/news HTTP/1.1
|
||||
POST https://dev-news.krgamestudios.com/news HTTP/1.1
|
||||
Content-Type: application/json
|
||||
Authorization: Bearer
|
||||
|
||||
{
|
||||
"title": "Hello World",
|
||||
"author": "Kayne Ruse",
|
||||
"author": "Anonymous",
|
||||
"body": "Lorem ipsum."
|
||||
}
|
||||
|
||||
###
|
||||
|
||||
#Edit
|
||||
PATCH https://dev-news.eggtrainer.com/news/1 HTTP/1.1
|
||||
PATCH https://dev-news.krgamestudios.com/news/1 HTTP/1.1
|
||||
Content-Type: application/json
|
||||
Authorization: Bearer
|
||||
|
||||
@@ -28,6 +39,6 @@ Authorization: Bearer
|
||||
###
|
||||
|
||||
#Delete
|
||||
DELETE https://dev-news.eggtrainer.com/news/1 HTTP/1.1
|
||||
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
|
||||
@@ -1,54 +0,0 @@
|
||||
#Login to the auth-server
|
||||
POST http://127.0.0.1:3200/auth/login HTTP/1.1
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"email": "kayneruse@gmail.com",
|
||||
"password": "helloworld"
|
||||
}
|
||||
|
||||
###
|
||||
|
||||
#Refresh from the auth-server
|
||||
POST http://127.0.0.1:3200/auth/token HTTP/1.1
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"token": ""
|
||||
}
|
||||
|
||||
###
|
||||
|
||||
#Query
|
||||
GET http://127.0.0.1:3100/news HTTP/1.1
|
||||
|
||||
###
|
||||
|
||||
#Publish
|
||||
POST http://127.0.0.1:3100/news HTTP/1.1
|
||||
Content-Type: application/json
|
||||
Authorization: Bearer
|
||||
|
||||
{
|
||||
"title": "Hello World",
|
||||
"author": "Kayne Ruse",
|
||||
"body": "Lorem ipsum dolor sit amet..."
|
||||
}
|
||||
|
||||
###
|
||||
|
||||
#Edit
|
||||
PATCH http://127.0.0.1:3100/news/5 HTTP/1.1
|
||||
Content-Type: application/json
|
||||
Authorization: Bearer
|
||||
|
||||
{
|
||||
"title": "Goodnight World"
|
||||
}
|
||||
|
||||
###
|
||||
|
||||
#Delete
|
||||
DELETE http://127.0.0.1:3100/news/4 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