All files / daos contents.ts

90.91% Statements 50/55
64.29% Branches 9/14
100% Functions 23/23
91.49% Lines 43/47

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247      1x   1x                         1x                 3x                       1x                 4x                 1x             1x               2x           2x                 10x                 3x 3x 3x       3x 1x   2x                           2x               2x 2x   2x   2x           2x   1x     1x               2x                   2x                 2x               2x 2x 2x 2x         2x 2x 2x                     2x       2x         2x                                       2x 2x 2x       2x 2x                      
import { MyModels } from "../models";
import { DumpsterContentsAttributes } from "../models/DumpsterContents";
import Content from "../types/Content";
import { NotFoundError, ServerError, UnknownError } from "../types/errors";
 
const contentAttributes = [
    "dumpsterID",
    "amount",
    "unit",
    "quality",
    "expiryDate",
    "foundDate",
    // avoiding DumpsterPositionDumpsterID, the unspeakable horror
];
 
/**
 * Maps the result of a findAll to an actual Content object.
 */
const toContent = ({
    amount,
    unit,
    quality,
    expiryDate,
    foundDate,
    contentType,
}: DumpsterContentsAttributes & {
    contentType: { name: string };
}): Content => ({
    name: contentType.name,
    amount,
    unit,
    quality,
    expiryDate,
    foundDate,
});
 
/**
 * Maps the result of a create call to an actual Content object.
 */
const createResultToContent = (
    name: string,
    {
        amount,
        unit,
        quality,
        expiryDate,
        foundDate,
    }: DumpsterContentsAttributes,
): Content => ({
    name,
    amount,
    unit,
    quality,
    expiryDate,
    foundDate,
});
 
export default function({
    ContentTypes,
    DumpsterContents,
    StandardContentTypes,
    DumpsterPositions,
    sequelize,
}: MyModels) {
    return {
        /**
         * Find all standard types of contents,
         * to present to users when they wanna add contents.
         *
         * Returns a little more than just the name, in case we *need* more.
         */
        getStandardContentTypes: () =>
            StandardContentTypes.findAll({
                include: {
                    model: ContentTypes,
                    as: "contentType",
                },
            }).then(data =>
                data.map(
                    // @ts-ignore
                    ({
                        contentID,
                        // @ts-ignore
                        contentType: { categoryID, name },
                    }: {
                        contentID: number;
                        contentType: { categoryID: number; name: string };
                    }) => ({ contentID, categoryID, name }),
                ),
            ),
 
        /**
         * Find the registered contents of a dumpster
         *
         * @param dumpsterID - ID of the queried dumpster
         */
        getAll: async (dumpsterID: number) => {
            return await sequelize.transaction(async t => {
                const dumpsterPosition = await DumpsterPositions.findOne({
                    where: { dumpsterID },
                    transaction: t,
                });
                if (!dumpsterPosition)
                    throw new NotFoundError("No such dumpster");
 
                return await DumpsterContents.findAll({
                    where: { dumpsterID },
                    attributes: contentAttributes,
                    include: [
                        {
                            model: ContentTypes,
                            as: "contentType",
                        },
                    ],
                    limit: 100,
                    order: [["foundDate", "DESC"]],
                    transaction: t,
                }).then(data =>
                    // @ts-ignore
                    data.map(toContent),
                );
            });
        },
 
        addOne: async (
            dumpsterID: number,
            content: Omit<Content, "foundDate">,
        ) => {
            const { name } = content;
 
            return await sequelize.transaction(async t => {
                // First, check if the content type already exists
                const match = await ContentTypes.findOne({
                    where: { name },
                    transaction: t,
                });
 
                let contentID;
                if (match) {
                    // If it does, we have the content type ID
                    contentID = match.contentID;
                } else {
                    // Otherwise, we'll have to add a new content type
                    contentID = (await ContentTypes.create(
                        // TODO either scrap category binding or find a way to set it...
                        { categoryID: 1, name },
                        { transaction: t },
                    )).contentID;
                }
 
                // Create the content entry
                await DumpsterContents.create(
                    {
                        dumpsterID,
                        contentID,
                        ...content,
                    },
                    { transaction: t },
                );
                // Then fetch the current data to get its date...
                // (kinda cursed, I know)
                const result = await DumpsterContents.findOne({
                    attributes: contentAttributes,
                    where: {
                        dumpsterID,
                        contentID,
                    },
                    order: [["foundDate", "DESC"]],
                    transaction: t,
                });
                Eif (result) return createResultToContent(name, result);
                else
                    throw new UnknownError(
                        "Content was not created (for unknown reasons)",
                    );
            });
        },
 
        updateOne: async (dumpsterID: number, content: Content) => {
            const { name, foundDate, ...editableAttributes } = content;
            return await sequelize.transaction(async t => {
                const match = await ContentTypes.findOne({
                    where: { name },
                    transaction: t,
                });
 
                Eif (match) {
                    const { contentID } = match;
                    const [numberUpdated, _] = await DumpsterContents.update(
                        editableAttributes,
                        {
                            where: {
                                dumpsterID,
                                contentID,
                                foundDate,
                            },
                            transaction: t,
                        },
                    );
                    Iif (numberUpdated > 1)
                        throw new ServerError(
                            `Updated ${numberUpdated} content entries, but no more than one should be updated`,
                        );
                    const result = await DumpsterContents.findOne({
                        attributes: contentAttributes,
                        where: { dumpsterID, contentID, foundDate },
                        transaction: t,
                    });
                    Eif (result) return createResultToContent(name, result);
                    else
                        throw new NotFoundError(
                            "Couldn't find a content entry with this data",
                        );
                } else {
                    throw new NotFoundError("No such content type");
                }
            });
        },
 
        /**
         * Removes a content entry
         * @param dumpsterID - ID of the dumpster the content was found in
         * @param name       - content type, for identification
         * @param foundDate  - date found, for identification
         */
        removeOne: async (
            dumpsterID: number,
            { name, foundDate }: Pick<Content, "name" | "foundDate">,
        ) => {
            return await sequelize.transaction(async t => {
                const match = await ContentTypes.findOne({
                    where: { name },
                    transaction: t,
                });
                Iif (!match) throw new NotFoundError("No such content type");
                return await DumpsterContents.destroy({
                    where: {
                        dumpsterID,
                        contentID: match.contentID,
                        foundDate,
                    },
                });
            });
        },
    };
}