[enh] There should be a db init/seed functionality

This commit is contained in:
alban 2020-05-23 19:32:32 +02:00
parent 8ecf1dfb7c
commit 56ce8cb645
2 changed files with 101 additions and 0 deletions

95
dbInit/index.js Normal file
View File

@ -0,0 +1,95 @@
// dbInit/index.js
"use strict"
const dbInit = {};
const bulkData = [
{ "index" : { "_index" : "changelog" } },
{ "author" : "John Ripper <john@theripper.com",
"content":"* machines: Installed the server\n```debootstrap -t foobar```",
"server": "server.example.com",
"created_at":"2020-05-23T09:50:33.397Z"},
{ "index" : { "_index" : "changelog" } },
{ "author" : "John Ripper <john@theripper.com",
"content":"* db: Installed mysql\n```apt install mariadb-server```",
"server": "server.example.com",
"created_at":"2020-05-23T10:50:33.397Z"},
{ "index" : { "_index" : "changelog" } },
{ "author" : "John Ripper <john@theripper.com",
"content":"* nginx: add package\n```apt install nginx-full```",
"server": "server.example.com",
"created_at":"2020-05-23T16:50:33.397Z"}
];
const mappings = {
"properties": {
"author": { "type": "keyword" },
"server": { "type": "keyword" },
"content": { "type": "text" },
"created_at": { "type": "date","format": "date_optional_time" }
}};
const elasticsearch = require('elasticsearch');
var client = new elasticsearch.Client({
host: process.env.ES_CONNECT,
// log: 'trace',
apiVersion: '7.7'
});
dbInit.client = client;
dbInit.bulkData = bulkData;
dbInit.mappings = mappings;
/**
*
* @param {object} flags
* @returns {int}
*/
dbInit.init = function( flags = {} ){
var seed = flags.seed || true;
this.client.indices.create({
index : "changelog",
body: {
mappings: this.mappings
}
}).then( (result) => {
console.log( "Index 'changelog' created with success.");
// seed if flag ok
if( ! seed ){ return true; };
this.client.bulk({
index: "changelog",
body: this.bulkData
}).then( (r) => {
console.log( "bulk insert OK");
}, (r) => {
console.log( "bulk insert ERROR! : ",r);
});
},( result ) => {
console.log( "Index 'changelog' already exists, skipping.");
});
this.client.indices.create({
index : "changelog-trash",
body: {
mappings: this.mappings
}
}).then( (result) => {
console.log( "Index 'changelog-trash' created with success.");
},( result ) => {
console.log( "Index changelog-trash exists, skipping.");
});
};
module.exports = dbInit;
// EOF

View File

@ -24,6 +24,12 @@ curl -X PUT 'http://localhost:9200/changelog' -d '
const authorizationToken = process.env.AUTH_TOKEN || "hello"; const authorizationToken = process.env.AUTH_TOKEN || "hello";
const port = process.env.APP_PORT || 3000; const port = process.env.APP_PORT || 3000;
const dbInit = require("./dbInit");
dbInit.init({
seed : process.env.DB_SEED
});
console.log( "exit")
const express = require('express'); const express = require('express');
const app = express(); const app = express();