- npm updates

- throw error exception if, there is no db connection
This commit is contained in:
Arno Kaimbacher 2023-04-27 15:58:45 +02:00
parent 77d620bdbd
commit df6f05a032
4 changed files with 93 additions and 67 deletions

View File

@ -7,6 +7,7 @@ import { DatasetController } from "./controllers/dataset.controller";
import { OaiController } from "./controllers/oai.controller"; import { OaiController } from "./controllers/oai.controller";
import { FileController } from "./controllers/file.controller"; import { FileController } from "./controllers/file.controller";
import * as path from "path"; import * as path from "path";
import HTTPException from "./exceptions/HttpException.js";
export class App extends Server { export class App extends Server {
// private app; // private app;
@ -66,12 +67,14 @@ export class App extends Server {
response.sendFile("/home/administrator/tethys.api/new-book.html"); response.sendFile("/home/administrator/tethys.api/new-book.html");
}); });
// Error handling middleware // // Error handling middleware
// this.app.use(errorHandler); // registration of handler // this.app.use(errorHandler); // registration of handler
// this.app.use((err: HTTPException, req: Request, res: Response, next: NextFunction) => { // Error handling middleware
// console.log('Oops !!, Error occured in req->res cycle ', err.message); this.app.use((error: HTTPException, req: express.Request, res: express.Response) => {
// res.status(err.status).json({ err }); // Send back Error to the Frontend console.log("Oops !!, Error occured in req->res cycle ", error.message);
// }) const status = error.status || 500;
res.status(status).json(error.message); // Send back Error to the Frontend
});
}) })
.catch((err) => { .catch((err) => {
console.error("Unable to connect to the database:", err); console.error("Unable to connect to the database:", err);

View File

@ -3,7 +3,7 @@ import dbContext from "../models/init-models.js";
import { Dataset, User, Person } from "../models/init-models.js"; import { Dataset, User, Person } from "../models/init-models.js";
import Sequelize from "sequelize"; import Sequelize from "sequelize";
const Op = Sequelize.Op; const Op = Sequelize.Op;
import { Request, Response } from "express"; import { NextFunction, Request, Response } from "express";
// import Logger from 'jet-logger'; // import Logger from 'jet-logger';
import { StatusCodes } from "http-status-codes"; import { StatusCodes } from "http-status-codes";
@ -22,7 +22,7 @@ export class DatasetController {
order: ["server_date_published"], order: ["server_date_published"],
}) })
.then((data) => { .then((data) => {
res.send(data); res.status(StatusCodes.OK).send(data);
}) })
.catch((err) => { .catch((err) => {
res.status(500).send({ res.status(500).send({
@ -32,44 +32,59 @@ export class DatasetController {
} }
@Get(":publish_id") @Get(":publish_id")
public async findOne(req: Request, res: Response) { public async findOne(req: Request, res: Response, next: NextFunction) {
const publish_id = req.params.publish_id; const publish_id = req.params.publish_id;
const dataset = await dbContext.Dataset.findOne({ try {
where: { publish_id: publish_id }, const dataset = await dbContext.Dataset.findOne({
include: [ where: { publish_id: publish_id },
"titles", include: [
"abstracts", "titles",
{ "abstracts",
model: User, {
as: "user", model: User,
}, as: "user",
{ },
model: Person, {
through: { where: { role: "author" } }, model: Person,
as: "authors", through: { where: { role: "author" } },
// order: [['link_documents_persons.sort_order', 'ASC']], as: "authors",
}, // order: [['link_documents_persons.sort_order', 'ASC']],
{ },
model: Person, {
through: { where: { role: "contributor" } }, model: Person,
as: "contributors", through: { where: { role: "contributor" } },
}, as: "contributors",
"subjects", },
"coverage", "subjects",
"licenses", "coverage",
"references", "licenses",
"project", "references",
"files", "project",
"identifier", "files",
], "identifier",
order: [ ],
["authors", dbContext.DocumentPersons, "sort_order", "ASC"], order: [
["contributors", dbContext.DocumentPersons, "sort_order", "ASC"], ["authors", dbContext.DocumentPersons, "sort_order", "ASC"],
], ["contributors", dbContext.DocumentPersons, "sort_order", "ASC"],
// order: ['server_date_published'], ],
// order: ['server_date_published'], // order: ['server_date_published'],
}); // order: ['server_date_published'],
});
if (dataset) {
res.status(StatusCodes.OK).send(dataset);
} else {
res.status(StatusCodes.NOT_FOUND).send({
message: `Cannot find Dataset with publish_id=${publish_id}.`,
});
}
} catch (error) {
// res.status(500).send({
// message: "Error retrieving Dataset with publish_id=" + publish_id,
// });
return next(error);
}
// .then((data) => { // .then((data) => {
// if (data) { // if (data) {
// res.send(data); // res.send(data);
@ -84,13 +99,13 @@ export class DatasetController {
// message: "Error retrieving Dataset with publish_id=" + publish_id, // message: "Error retrieving Dataset with publish_id=" + publish_id,
// }); // });
// }); // });
if (dataset) { // if (dataset) {
res.status(StatusCodes.OK).send(dataset); // res.status(StatusCodes.OK).send(dataset);
} else { // } else {
res.status(StatusCodes.NOT_FOUND).send({ // res.status(StatusCodes.NOT_FOUND).send({
message: `Cannot find Dataset with publish_id=${publish_id}.`, // message: `Cannot find Dataset with publish_id=${publish_id}.`,
}); // });
} // }
} }
} }

View File

@ -4,22 +4,26 @@ import Sequelize from "sequelize";
const Op = Sequelize.Op; const Op = Sequelize.Op;
import { Person } from "../models/init-models.js"; import { Person } from "../models/init-models.js";
export async function findYears(req, res) { export async function findYears(req, res, next) {
const serverState = "published"; const serverState = "published";
// Use raw SQL queries to select all cars which belongs to the user // Use raw SQL queries to select all cars which belongs to the user
const datasets = await sequelizeConnection.query( try {
"SELECT distinct EXTRACT(YEAR FROM server_date_published) as published_date FROM gba.documents WHERE server_state = (:serverState)", const datasets = await sequelizeConnection.query(
{ "SELECT distinct EXTRACT(YEAR FROM server_date_published) as published_date FROM gba.documents WHERE server_state = (:serverState)",
replacements: { serverState: serverState }, {
type: sequelizeConnection.QueryTypes.SELECT, replacements: { serverState: serverState },
// attributes: [[sequelizeConnection.fn('DISTINCT', sequelizeConnection.col('published_date')), 'alias_name']], type: sequelizeConnection.QueryTypes.SELECT,
}, // attributes: [[sequelizeConnection.fn('DISTINCT', sequelizeConnection.col('published_date')), 'alias_name']],
); },
// Pluck the ids of the cars );
const years = datasets.map((dataset) => dataset.published_date); // Pluck the ids of the cars
// check if the cars is returned const years = datasets.map((dataset) => dataset.published_date);
if (years.length > 0) { // check if the cars is returned
// if (years.length > 0) {
return res.status(200).json(years); return res.status(200).json(years);
// }
} catch (error) {
return next(error);
} }
} }

View File

@ -83,10 +83,14 @@ export class OaiController {
const xsltParameter = (this.xsltParameter = {}); const xsltParameter = (this.xsltParameter = {});
let earliestDateFromDb; let earliestDateFromDb;
const firstPublishedDataset: Dataset | null = await Dataset.earliestPublicationDate(); try {
firstPublishedDataset != null && const firstPublishedDataset: Dataset | null = await Dataset.earliestPublicationDate();
(earliestDateFromDb = dayjs(firstPublishedDataset.server_date_published).format("YYYY-MM-DDTHH:mm:ss[Z]")); firstPublishedDataset != null &&
this.xsltParameter["earliestDatestamp"] = earliestDateFromDb; (earliestDateFromDb = dayjs(firstPublishedDataset.server_date_published).format("YYYY-MM-DDTHH:mm:ss[Z]"));
this.xsltParameter["earliestDatestamp"] = earliestDateFromDb;
} catch (error) {
return next(error);
}
let oaiRequest: OaiParameter = {}; let oaiRequest: OaiParameter = {};
if (request.method == "POST") { if (request.method == "POST") {