All files / owid-grapher/db/model Post.ts

50.79% Statements 32/63
100% Branches 1/1
0% Functions 0/4
50.79% Lines 32/63

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 491x 1x 1x 1x 2x 2x 2x 2x     2x 2x 2x 2x                                       2x 2x                   2x 2x   2x 1x
import * as db from "../db"
import { Knex } from "knex"
import { PostRow } from "../../clientUtils/owidTypes"
 
export namespace Post {
    export const table = "posts"
 
    export const select = <K extends keyof PostRow>(
        ...args: K[]
    ): { from: (query: Knex.QueryBuilder) => Promise<Pick<PostRow, K>[]> } => ({
        from: (query) => query.select(...args) as any,
    })
 
    export const tagsByPostId = async (): Promise<
        Map<number, { id: number; name: string }[]>
    > => {
        const postTags = await db.queryMysql(`
            SELECT pt.post_id AS postId, pt.tag_id AS tagId, t.name as tagName FROM post_tags pt
            JOIN posts p ON p.id=pt.post_id
            JOIN tags t ON t.id=pt.tag_id
        `)

        const tagsByPostId: Map<number, { id: number; name: string }[]> =
            new Map()

        for (const pt of postTags) {
            const tags = tagsByPostId.get(pt.postId) || []
            tags.push({ id: pt.tagId, name: pt.tagName })
            tagsByPostId.set(pt.postId, tags)
        }

        return tagsByPostId
    }
 
    export const setTags = async (postId: number, tagIds: number[]) =>
        await db.transaction(async (t) => {
            const tagRows = tagIds.map((tagId) => [tagId, postId])
            await t.execute(`DELETE FROM post_tags WHERE post_id=?`, [postId])
            if (tagRows.length)
                await t.execute(
                    `INSERT INTO post_tags (tag_id, post_id) VALUES ?`,
                    [tagRows]
                )
        })
 
    export const bySlug = async (slug: string): Promise<PostRow | undefined> =>
        (await db.knexTable("posts").where({ slug: slug }))[0]
}