~jae/neos-headless-manager

38f8694ecc929c135d7af746f34e34388f47377a — Jae Lo Presti (DN0) 7 months ago 869e4c3
image: add working db population for images & return API result
4 files changed, 52 insertions(+), 4 deletions(-)

A src/routes/imageApi.ts
A src/utils/dbPopulate.ts
M src/utils/dockerUtils.ts
M src/utils/imageUtils.ts
A src/routes/imageApi.ts => src/routes/imageApi.ts +12 -0
@@ 0,0 1,12 @@
import {FastifyPluginCallback} from "fastify";
import {imageApiResponseGenerator} from "../utils/imageUtils";

const plugin: FastifyPluginCallback = (fastify, opts, next): void => {
    fastify.get("/api/v1/images", async(request, reply) => {
        await reply.type('application/json').send(await imageApiResponseGenerator());
    });
    
    next();
}

export default plugin;
\ No newline at end of file

A src/utils/dbPopulate.ts => src/utils/dbPopulate.ts +28 -0
@@ 0,0 1,28 @@
import {getImages} from "./dockerUtils";
import {dbConn} from "./dbUtils";
import {generateLogger} from "./loggerUtils";

const log = generateLogger('dbPopulate.ts');

const populateDBImages = async (): Promise<void> => {
    const db = dbConn();
    
    getImages(true).then(imageList => {
        imageList.forEach(image => {
            log.info(`Populating DB with image ${image.Id}`);
            
            db('images').insert({
                image_id: image.Id,
                image_tag: image.RepoTags[0],
            }).then(res => {
                log.info(res);
            }).catch(e => {
                log.error(e);
            });
        });
    });
}

populateDBImages().then(_res => {
    log.info('DB populated!');
});
\ No newline at end of file

M src/utils/dockerUtils.ts => src/utils/dockerUtils.ts +3 -3
@@ 52,12 52,12 @@ export const stopSingleServer = (serverId: string): void => {
    }).catch(e => log.error(e));
}

export const getImages = async (): Promise<string[]> => {
export const getImages = async (skipChecks?: boolean): Promise<Dockerode.ImageInfo[]> => {
    const allImages = await dockerDaemon.listImages();

    return allImages.map((image) => {
        if (image.RepoTags.find(name => name.includes('neos')))
            return image.Id;
        if (image.RepoTags.find(name => name.includes('neos') || skipChecks))
            return image;
    })
}


M src/utils/imageUtils.ts => src/utils/imageUtils.ts +9 -1
@@ 1,9 1,17 @@
import {ImageTable} from "../types/dbTypes";

import {dbConn} from "./dbUtils";
import {generateLogger} from "./loggerUtils";

const log = generateLogger('imageUtils.ts');

export const fetchImages = async (): Promise<readonly ImageTable[]> => {
    const db = dbConn();
    
    return await db<ImageTable>('images').select('*');
}
\ No newline at end of file
}

export const imageApiResponseGenerator = async (): Promise<string> => {
    const payload = await fetchImages();
    return JSON.stringify(payload);
}