Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow adding answers to questions #82

Merged
merged 3 commits into from
Aug 10, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 29 additions & 5 deletions src/database.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ import { setUpAssociations } from "./associations";
import { initializeModels } from "./models";
import { StudentOption, StudentOptions } from "./models/student_options";
import { Question } from "./models/question";
import { logger } from "./logger";

type SequelizeError = { parent: { code: string } };

Expand Down Expand Up @@ -601,15 +602,38 @@ export async function setStudentOption(studentID: number, option: StudentOption,
}

export async function findQuestion(tag: string, version?: number): Promise<Question | null> {
const whereQuery: WhereOptions = { tag };
if (version !== undefined) {
whereQuery["version"] = version;
return Question.findOne({ where: { tag, version } });
} else {
const questions = await Question.findAll({
where: { tag },
order: [["version", "DESC"]],
limit: 1
});
return questions[0] ?? null;
}
return Question.findOne({ where: whereQuery });
}

export async function addQuestion(tag: string, text: string, shorthand: string, story_name: string, version?: number): Promise<Question | null> {
return Question.create({ tag, text, shorthand, story_name, version: version || 1 }).catch((_error) => null);
interface QuestionInfo {
tag: string;
text: string;
shorthand: string;
story_name: string;
answers_text?: string[];
correct_answers?: number[];
neutral_answers?: number[];
version?: number;
}
export async function addQuestion(info: QuestionInfo): Promise<Question | null> {
if (!info.version) {
const currentVersion = await currentVersionForQuestion(info.tag);
info.version = currentVersion || 1;
}
return Question.create(info).catch((error) => {
logger.error(error);
logger.error(`Question info: ${JSON.stringify(info)}`);
return null;
});
}

export async function currentVersionForQuestion(tag: string): Promise<number | null> {
Expand Down
15 changes: 15 additions & 0 deletions src/models/question.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ export class Question extends Model<InferAttributes<Question>, InferCreationAttr
declare story_name: string;
declare version: CreationOptional<number>;
declare created: CreationOptional<Date>;
declare answers_text: CreationOptional<string[]>;
declare correct_answers: CreationOptional<number[]>;
declare neutral_answers: CreationOptional<number[]>;
}

export function initializeQuestionModel(sequelize: Sequelize) {
Expand Down Expand Up @@ -49,6 +52,18 @@ export function initializeQuestionModel(sequelize: Sequelize) {
type: DataTypes.DATE,
allowNull: false,
defaultValue: Sequelize.literal("CURRENT_TIMESTAMP")
},
answers_text: {
type: DataTypes.JSON,
defaultValue: null
},
correct_answers: {
type: DataTypes.JSON,
defaultValue: null
},
neutral_answers: {
type: DataTypes.JSON,
defaultValue: null
}
}, {
sequelize,
Expand Down
11 changes: 9 additions & 2 deletions src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ import { v4 } from "uuid";
import cors from "cors";
import jwt from "jsonwebtoken";
import { isStudentOption } from "./models/student_options";
import { isNumberArray, isStringArray } from "./utils";
export const app = express();

// TODO: Clean up these type definitions
Expand Down Expand Up @@ -505,11 +506,17 @@ app.post("/question/:tag", async (req, res) => {
const text = req.body.text;
const shorthand = req.body.shorthand;
const story_name = req.body.story_name;
const answers_text = req.body.answers_text;
const correct_answers = req.body.correct_answers;
const neutral_answers = req.body.neutral_answers;

const valid = typeof tag === "string" &&
typeof text === "string" &&
typeof shorthand === "string" &&
typeof story_name === "string";
typeof story_name === "string" &&
(answers_text === undefined || isStringArray(answers_text)) &&
(correct_answers === undefined || isNumberArray(correct_answers)) &&
(neutral_answers === undefined || isNumberArray(neutral_answers));
if (!valid) {
res.statusCode = 400;
res.json({
Expand All @@ -520,7 +527,7 @@ app.post("/question/:tag", async (req, res) => {

const currentQuestion = await findQuestion(tag);
const version = currentQuestion !== null ? currentQuestion.version + 1 : 1;
const addedQuestion = await addQuestion(tag, text, shorthand, story_name, version);
const addedQuestion = await addQuestion({tag, text, shorthand, story_name, answers_text, correct_answers, neutral_answers, version});
if (addedQuestion === null) {
res.statusCode = 500;
res.json({
Expand Down
3 changes: 3 additions & 0 deletions src/sql/create_questions_table.sql
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@ CREATE TABLE Questions (
story_name varchar(50) NOT NULL,
version int(11) NOT NULL DEFAULT 1,
created datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
answers_text JSON DEFAULT NULL,
correct_answers JSON DEFAULT NULL,
neutral_answers JSON DEFAULT NULL,

PRIMARY KEY(id),
INDEX(tag),
Expand Down
10 changes: 10 additions & 0 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,13 @@ export function createClassCode(educatorID: number, className: string) {
const nameString = `${educatorID}_${className}`;
return createV5(nameString);
}

// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function isNumberArray(arr: any): arr is number[] {
return Array.isArray(arr) && arr.every(x => typeof x === "number");
}

// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function isStringArray(arr: any): arr is string[] {
return Array.isArray(arr) && arr.every(x => typeof x === "string");
}