I'm calling for your help today because I can't put the data in mongo db, indeed, I managed to connect, but impossible to add the data.
I'm going to explain you a little bit my code, in a first time, I'm going to search the pages according to a start number and an end number, the first function is going to search if the page exists or not, in my 2nd function search, then I'm going to search the category I'm interested in, then I'm going to get the information of this page, that is to say what you can see in the "const contact", then I'm going to add all this in a db file.
So what I want is instead of putting it in the db file it automatically adds me to mongodb.
// import
const Datastore = require('nedb')
// const fs = require('fs')
const puppeteer = require('puppeteer');
const fs = require('fs');
const { resolve } = require('path');
// global variables
var totalFound = 0
var headless = true
const DB_PATH = './huarenjietest2.db' //addition in the db file
const START_LINK = 'https://www.huarenjiewang.com/info-[pageIndex].html'
const LOCATION_SeleCTOR = 'body > div.body1000 > div.location'
const COOKIE_SELECTOR = 'body > div.fc-consent-root > div.fc-dialog-container > div.fc-dialog.fc-choice-dialog > div.fc-dialog-content > div > div.fc-header.fc-dialog-restricted-content > h1'
const NotFoundSelector = 'body > div > div.tip-bgC > div'
const phoneSelector = '#show-phone'
const workTypeSelector = 'body > div.body1000 > div.wrapper > div.information_bd > div.bd_left > div.extra_contact > div > ul > li:nth-child(4)'
const zoneSelector = 'body > div.body1000 > div.wrapper > div.information_bd > div.bd_left > div.extra_contact > div > ul > li:nth-child(1)'
const whoSelector = 'body > div.body1000 > div.wrapper > div.information_bd > div.bd_left > div.extra_contact > div > ul > li:nth-child(6) > span.faburen > a:nth-child(1)'
const infoSelector = 'body > div.body1000 > div.wrapper > div.information_bd > div.bd_left > div.view_bd > p'
const dateSeloctor = 'body > div.body1000 > div.wrapper > div.information_bd > div.bd_left > div.information_hd > div.my_yp_view_title2 > div.my_yp_view_title2_l'
const COOKIE_BUTTON = 'body > div.fc-consent-root > div.fc-dialog-container > div.fc-dialog.fc-choice-dialog > div.fc-footer-buttons-container > div.fc-footer-buttons > button.fc-button.fc-cta-consent.fc-primary-button'
//mongodb
var express = require("express")
const database = require('./config/database')
var router = express.Router();
const Huarenjiemongo = require("./model/huarenjiemodel")
database.connection()
// command line options
const optionDefinitions = [
{ name: 'headless', type: Boolean },
{ name: 'start', type: Number },
{ name: 'end', type: Number },
{ name: 'export', type: String },
]
const commandLineArgs = require('command-line-args');
const { exit } = require('process');
const { mongo } = require('mongoose');
const options = commandLineArgs(optionDefinitions)
const startIndex = options.start
const endIndex = options.end
const outputPath = options.export
if(!startIndex || !endIndex){
console.log('use command like : node huarenjie.js --start 12321323 --end 13321323 --export output.csv')
exit()
}
const dbPath = DB_PATH
const db = new Datastore({ filename: dbPath, autoload: true })
db.ensureIndex({ fieldName: 'infoIndex', unique: true }, function (err) {
if (err) {
console.log('ensureIndex error :', err)
}
})
function dateyyyyMMdd(d, separate = '') {
let date = d
var mm = date.getMonth() + 1 // getMonth() is zero-based
var dd = date.getDate()
return [date.getFullYear(), (mm > 9 ? '' : '0') + mm, (dd > 9 ? '' : '0') + dd].join(separate)
}
database.connection();
function delay(time) {
return new Promise(function(resolve) {
setTimeout(resolve, time)
});
}
async function checkPageExite(page){
return new Promise((resolve, reject) => {
page.waitForSelector(LOCATION_SeleCTOR).then(() => {
resolve(true)
}).catch(()=> { resolve(false)})
page.waitForSelector(NotFoundSelector).then(() => {
console.info('page not exist')
resolve(false)
}).catch(()=> { resolve(false)})
page.waitForSelector(COOKIE_BUTTON).then(() => {
return Promise.resolve()
}).then(() => {
return page.$eval( COOKIE_BUTTON, form => form.click() )
}).then(() => {
if(page.url() === 'https://www.huarenjiewang.com/changecity.php'){
resolve(false)
} else {
resolve(true)
}
}).catch(()=> { resolve(false)})
})
}
async function search() {
const browser = await puppeteer.launch({ headless: headless })
console.log('====> Puppeteer started')
const page = await browser.newPage();
await page.setViewport({ width: 1280, height: 800 })
for(var i=startIndex;i<=endIndex;i++){
try {
console.info(`====== index : ${i} ========`)
await page.goto(START_LINK.replace('[pageIndex]',i))
// await page.waitForSelector(LOCATION_SeleCTOR)
const exist = await checkPageExite(page)
if(exist === 'skip'){
continue
}
if(exist === true){
let element = await page.$(LOCATION_SeleCTOR)
let categoryValue = await page.evaluate(el => el.textContent, element)
if(categoryValue.includes('appartement/louer')){
let phone = await page.$(phoneSelector)
let phoneValue = await page.evaluate(el => el.getAttribute("data-phone"), phone)
if(phoneValue){
let workElement = await page.$(workTypeSelector)
let workValue = await page.evaluate(el => el.textContent, workElement)
let zoneElement = await page.$(zoneSelector)
let zoneValue = await page.evaluate(el => el.textContent, zoneElement)
let whoElement = await page.$(whoSelector)
let whoValue = await page.evaluate(el => el.textContent, whoElement)
let infoElement = await page.$(infoSelector)
let infoValue = await page.evaluate(el => el.textContent, infoElement)
let dateElement = await page.$(dateSeloctor)
var dateValue = await page.evaluate(el => el.textContent, dateElement)
var date
var dateStr
var reg1 = /(\d{4}-\d{2}-\d{2})/
const found1 = dateValue.match(reg1)
if(found1 && found1.length > 1){
dateStr = found1[1]
}
if(dateValue.includes('昨天')){
var date = new Date()
date.setDate(date.getDate() -1)
dateStr = dateyyyyMMdd(date,'-')
}
if(dateValue.includes('前天')){
var date = new Date()
date.setDate(date.getDate() -2)
dateStr = dateyyyyMMdd(date,'-')
}
const contact = {
phone : phoneValue,
zone: zoneValue,
workType: workValue,
who: whoValue,
info: infoValue,
date: dateStr || '',
infoIndex: i
}
db.update({ infoIndex: i }, { $set: contact }, { upsert: true }, function () {});
console.info(`${i}#############>saved`)
} else {
console.info(`${i}=>skip==>phone number missing`)
}
} else {
console.info(`${i}=>skip==>category not correct`)
}
if(categoryValue.includes('maison/louer')){
let phone = await page.$(phoneSelector)
let phoneValue = await page.evaluate(el => el.getAttribute("data-phone"), phone)
if(phoneValue){
let workElement = await page.$(workTypeSelector)
let workValue = await page.evaluate(el => el.textContent, workElement)
let zoneElement = await page.$(zoneSelector)
let zoneValue = await page.evaluate(el => el.textContent, zoneElement)
let whoElement = await page.$(whoSelector)
let whoValue = await page.evaluate(el => el.textContent, whoElement)
let infoElement = await page.$(infoSelector)
let infoValue = await page.evaluate(el => el.textContent, infoElement)
let dateElement = await page.$(dateSeloctor)
var dateValue = await page.evaluate(el => el.textContent, dateElement)
var date
var dateStr
var reg1 = /(\d{4}-\d{2}-\d{2})/
const found1 = dateValue.match(reg1)
if(found1 && found1.length > 1){
dateStr = found1[1]
}
if(dateValue.includes('昨天')){
var date = new Date()
date.setDate(date.getDate() -1)
dateStr = dateyyyyMMdd(date,'-')
}
if(dateValue.includes('前天')){
var date = new Date()
date.setDate(date.getDate() -2)
dateStr = dateyyyyMMdd(date,'-')
}
const contact = {
phone : phoneValue,
zone: zoneValue,
workType: workValue,
who: whoValue,
info: infoValue,
date: dateStr || '',
infoIndex: i
}
db.update({ infoIndex: i }, { $set: contact }, { upsert: true }, function () {})
console.info(`${i}#############>saved-tech`)
} else {
console.info(`${i}=>skip==>phone number missing`)
}
} else {
console.info(`${i}=>skip==>category not correct`)
}
}
// await delay(5000)
} catch (error) {
console.info(`${i}=>error read page:`, error)
}
}
}
const connectToMongoDB = async() => {
await database().then(async (mongoose) => {
try {
console.log('Connecto to mongodb')
db.collection({ infoIndex: i }, { $set: contact }, { upsert: true }, function () {})
await new huarenjieShema(contact).save()
} finally {
mongoose.connection.close()
}
})
}
connectToMongoDB()
async function main() {
if(outputPath){
db.find({ "infoIndex": { $gte: startIndex , $lte: endIndex} }, function (err, docs) {
if(err){
console.error(err)
} else {
var body = `infoIndex;who;phone;zone;workType;comment\n`
for(var doc of docs){
body += `${doc.infoIndex};${(doc.who || '').trim()};${doc.phone};${(doc.zone || '').trim()};${(doc.workType || '').trim()};${(doc.info || '').trim()}\n`
}
fs.writeFileSync(options.export, body)
}
exit()
});
} else {
await search()
}
console.info('>>>>> Finished')
console.info('>>>>> totalFound:', totalFound)
}
main()
here is the model
const mongoose = require('mongoose')
const huarenjieShenma = mongoose.Schema({
infoIndex: {
type: Number,
unique: true,
},
who: {
type: String,
},
phone: {
type: Number,
},
zone: {
type: String,
},
workType: {
type: String,
},
comment: {
type: String,
},
})
module.exports = mongoose.model('Huarenjie', huarenjieShenma)
I will not check your whole code. Just a small hint how to insert data to your collection using your schema.
const huarenjieShenma = mongoose.Schema({
infoIndex: {
type: Number,
unique: true,
},
who: {
type: String,
},
phone: {
type: Number,
},
zone: {
type: String,
},
workType: {
type: String,
},
comment: {
type: String,
},
})
const Huarenjie = mongoose.model('Huarenjie', huarenjieShenma);
const testObject = {
infoIndex: 1,
who: "Me",
phone: 555666777, //im my opinion phone is not a number
zone: "Area 51",
workType: "WorkType",
comment: "Just a comment"
};
(async () => {
const newObject = await Huarenjie.create(testObject);
console.log(newObject);
})();
Related
So I literally copied from
(https://docs.solana.com/developing/clients/javascript-api)
I need to send a transaction from one wallet to another, easy right? But this doest work here
error
Specifically, the transfer method cannot create an instruction. I've tried everything I can, but it hasn't worked. Please help dear programmers
MY CODE:
async function transfer() {
const provider = await IsConnected();
console.log(provider.publicKey.toString());
const connection = new solanaWeb3.Connection(
"https://api.devnet.solana.com",
"confirmed"
);
var recieverWallet = new solanaWeb3.PublicKey(
"3uePV7kJcT3w5qMLPTHVAdLc72SF2iDRwNcxDE713EMf"
);
// var airdropSignature = await connection.requestAirdrop(
// provider.publicKey,
// solanaWeb3.LAMPORTS_PER_SOL * 0.4
// );
// await connection
// .confirmTransaction(airdropSignature)
// .then(console.log("Airdropped"));
var transaction = new solanaWeb3.Transaction();
transaction.feePayer = await provider.publicKey;
let blockhashObj = await connection.getRecentBlockhash();
transaction.recentBlockhash = await blockhashObj.blockhash;
transaction.add(
await solanaWeb3.SystemProgram.transfer({
fromPubkey: provider.publicKey,
toPubkey: recieverWallet,
lamports: 10000,
})
);
if (transaction) {
console.log("Txn created successfully");
}
let signed = await provider.signTransaction(transaction).serialize();
let signature = await connection.sendRawTransaction(signed);
console.log(signature);
let bConfirmed = await connection.confirmTransaction(signature);
console.log(bConfirmed);
}
CODE WHERE PROBLEM:
static transfer(
params: TransferParams | TransferWithSeedParams,
): TransactionInstruction {
let data;
let keys;
if ('basePubkey' in params) {
const type = SYSTEM_INSTRUCTION_LAYOUTS.TransferWithSeed;
data = encodeData(type, {
lamports: BigInt(params.lamports),
seed: params.seed,
programId: toBuffer(params.programId.toBuffer()),
});
keys = [
{pubkey: params.fromPubkey, isSigner: false, isWritable: true},
{pubkey: params.basePubkey, isSigner: true, isWritable: false},
{pubkey: params.toPubkey, isSigner: false, isWritable: true},
];
} else {
const type = SYSTEM_INSTRUCTION_LAYOUTS.Transfer;
***THERE ->*** data = encodeData(type, {lamports: BigInt(params.lamports)});
keys = [
{pubkey: params.fromPubkey, isSigner: true, isWritable: true},
{pubkey: params.toPubkey, isSigner: false, isWritable: true},
];
}
return new TransactionInstruction({
keys,
programId: this.programId,
data,
});
}
export function encodeData<TInputData extends IInstructionInputData>(
type: InstructionType<TInputData>,
fields?: any,
): Buffer {
const allocLength =
type.layout.span >= 0 ? type.layout.span : Layout.getAlloc(type, fields);
const data = Buffer.alloc(allocLength);
const layoutFields = Object.assign({instruction: type.index}, fields);
type.layout.encode(layoutFields, data);
return data;
}
encode(src, b, offset = 0) {
const firstOffset = offset;
let lastOffset = 0;
let lastWrote = 0;
for (const fd of this.fields) {
let span = fd.span;
lastWrote = (0 < span) ? span : 0;
if (undefined !== fd.property) {
const fv = src[fd.property];
if (undefined !== fv) {
lastWrote = fd.encode(fv, b, offset);
if (0 > span) {
/* Read the as-encoded span, which is not necessarily the
* same as what we wrote. */
span = fd.getSpan(b, offset);
}
}
}
lastOffset = offset;
offset += span;
}
const bigInt =
(length: number) =>
(property?: string): Layout<bigint> => {
const layout = blob(length, property);
const {encode, decode} = encodeDecode(layout);
const bigIntLayout = layout as Layout<unknown> as Layout<bigint>;
bigIntLayout.decode = (buffer: Buffer, offset: number) => {
const src = decode(buffer, offset);
return toBigIntLE(Buffer.from(src));
};
bigIntLayout.encode = (bigInt: bigint, buffer: Buffer, offset: number) => {
const src = toBufferLE(bigInt, length);
return encode(src, buffer, offset);
};
return bigIntLayout;
};
function toBufferLE(num, width) {
{
const hex = num.toString(16);
const buffer = Buffer.from(hex.padStart(width * 2, '0').slice(0, width * 2), 'hex');
buffer.reverse();
return buffer;
}
// Allocation is done here, since it is slower using napi in C
return converter.fromBigInt(num, Buffer.allocUnsafe(width), false);
}
exports.toBufferLE = toBufferLE;
I keep getting Cannot read property 'date' of undefined when I call my getDataPrevDay function, but console.log(appointment[0].apps.date) logs the correct date
const admin = ({data}) => {
const [appointment, setAppointment] = useState(data);
console.log(appointment[0].apps.date)
const getDataPrevDay = async () => {
let currentDate = dayjs(appointment[0].apps.date).format('YYYY-MM-DD')
let newDate = dayjs(currentDate).subtract(1, 'day').format('YYYY-MM-DD')
const res = await fetch(`http://localhost:3000/api/appointmentsdb?
date=${newDate}`)
let json = await res.json();
setAppointment(json);
}
....
return (
<button onClick={getDataPrevDay}> Prev Day </button>
)
}
export async function getServerSideProps(context){
const currentDate = dayjs().format('YYYY-MM-DD')
const res = await fetch(`http://localhost:3000/api/appointmentsdb?date=${currentDate}`)
let json = await res.json();
json = json.map(apps => ({apps}))
return {
props: {
data: json
},
};}
this is the handler
handler.get(async (req, res) => {
const {date, first_name, last_name, number, email, time} =
req.query;
const dataModel =
{'_id': new ObjectID(),
'first_name': first_name,
'last_name': last_name,
'number': number,
'email': email,
'date': date,
'time': time
};
let doc = {}
if(date) {
doc = await req.db.collection('Info').find({date: date},
{projection : {_id: 0}}).toArray()
} else {
doc = await req.db.collection('Info').findOne()
} if(doc == null) {
doc = dataModel;
}
res.json(doc);
});
The prop is rendered and updated dynamically. You can add a fail safe to avoid uniterable values by skipping if they are null.
const admin = ({data}) => {
const [appointment, setAppointment] = useState(data);
console.log(appointment[0].apps.date)
const getDataPrevDay = async () => {
if(appointment && appointment.length && appointment[0].apps && appointment[0].apps.date) {
let currentDate = dayjs(appointment[0].apps.date).format('YYYY-MM-DD')
let newDate = dayjs(currentDate).subtract(1, 'day').format('YYYY-MM-DD')
const res = await fetch(`http://localhost:3000/api/appointmentsdb?
date=${newDate}`)
let json = await res.json();
setAppointment(json);
}
}
....
return (
<button onClick={getDataPrevDay}> Prev Day </button>
)
}
export async function getServerSideProps(context){
const currentDate = dayjs().format('YYYY-MM-DD')
const res = await fetch(`http://localhost:3000/api/appointmentsdb?date=${currentDate}`)
let json = await res.json();
json = json.map(apps => ({apps}))
return {
props: {
data: json
},
};}
So I want it to delete some specific messages if the date/Minutes is 55 and the month is this month! Although I got some Discord API errors as specified below! I was trying to make a delay and to make sure that the msg even exists but no luck it gave me the same error!
const ytdl = require('ytdl-core');
const editJsonFile = require("edit-json-file");
var fs = require('file-system');
var path = require('path');
const prefix = "v_";
let count;
exports.run = async (client, message, args, ops) => {
const channel = client.channels.cache.get("813794049445462036");
const channel2 = client.channels.cache.get("813801699469819984");
const channelog = client.channels.cache.get("814561365510586400");
const monthlog = client.channels.cache.get("814758448700719155");
let number = editJsonFile(`premium/premium.json`);
let endDate = editJsonFile(`premium/endate.json`);
let count = editJsonFile(`premium/count.json`);
let month = editJsonFile(`premium/month.json`);
month.save();
number.save();
endDate.save();
count.save();
count.set(`p`, 0);
count.set(`p1`, 0);
count.save();
let p = count.get(`p`);
let p1 = count.get(`p1`);
//Reset
setTimeout(async function() {
channel2.messages.fetch({ limit: 100 }).then(messages => {
messages.forEach(async message => {
p = count.get(`p`);
p1 = count.get(`p1`);
var today = new Date();
var date = today.getMinutes()
var montht = new Date();
var monthcheck = montht.getMonth();
if (date == 55) {
setTimeout(async function() {
monthlog.messages.fetch({ limit: 100 }).then(messages => {
messages.forEach(message3 => {
p = count.get(`p`);
p1 = count.get(`p1`);
console.log(monthcheck);
if (message3.content == 2) {
let number = editJsonFile(`premium/premium.json`);
number.save();
const userid2 = number.get(`${p1}`);
setTimeout(async function() {
if (message != undefined){
await message.delete({ timeout: 250 });
}
}, 0)
setTimeout(async function() {
if (message3 != undefined){
await message3.delete({ timeout: 500 });
}
}, 1000)
setTimeout(async function() {
channel.messages.fetch({ limit: 100 }).then(messages => {
messages.forEach(message2 => {
p = count.get(`p`);
p1 = count.get(`p1`);
console.log(userid2);
console.log(`${message2.content}`);
console.log(`${p1}`)
if(userid2 == message2.content) {
setTimeout(async function() {
await message2.delete({ timeout: 100 });
}, 0)
number = editJsonFile(`premium/premium.json`);
number.unset(`${p1}`)
number.save();
}
endDate.unset(`${p1}`);
endDate.save();
month.unset(`${p1}`);
month.save();
setTimeout(async function() {
channelog.send(`💿 <#${userid2}>'s premium has expired from partnering!'`)
}, 500)
message.delete();
})
})
}, 5000)
}
else {
p = count.get(`p`);
p1 = count.get(`p1`);
pf = count.get(`pf`);
pf1 = count.get(`pf1`);
if (p == p1) {
endDate.set(`${p1}`, message.content)
endDate.save();
month.set(`${p1}`, message3.content)
month.save();
}
else {
endDate.set(`${p1}`, message.content)
endDate.save();
month.set(`${p1}`, message3.content)
month.save();
count.set(`p1`, p1+1);
count.save();
}
}
})
})
}, 3000);
}
})
})
}, 5000)
setTimeout(function() {
channel.messages.fetch({ limit: 100 }).then(messages => {
messages.forEach(message => {
p = count.get(`p`);
p1 = count.get(`p1`);
number = editJsonFile(`premium/premium.json`);
number.set(`${p}`, message.content)
number.save();
count = editJsonFile(`premium/count.json`);
count.set(`p`, p+1);
count.save();
})
})
}, 1000)
count = editJsonFile(`premium/count.json`);
count.set(`p`, 0);
count.set(`p1`, 0);
count.save();
number.save();
}
This is the error I got for both of the times I tested with my code:
C:\Users\cedri\Desktop\vibe-main\node_modules\discord.js\src\rest\RequestHandler.js:154
throw new DiscordAPIError(request.path, data, request.method, res.status);
^
DiscordAPIError: Unknown Message
at RequestHandler.execute (C:\Users\cedri\Desktop\vibe-main\node_modules\discord.js\src\rest\RequestHandler.js:154:13)
at processTicksAndRejections (node:internal/process/task_queues:93:5)
at async RequestHandler.push (C:\Users\cedri\Desktop\vibe-main\node_modules\discord.js\src\rest\RequestHandler.js:39:14)
at async MessageManager.delete (C:\Users\cedri\Desktop\vibe-main\node_modules\discord.js\src\managers\MessageManager.js:126:5)
at async Timeout._onTimeout (C:\Users\cedri\Desktop\vibe-main\events\premium.js:60:23) {
method: 'delete',
path: '/channels/813801699469819984/messages/814796597518139413',
code: 10008,
httpStatus: 404
}
Unknown Message occurs most commonly when you are trying to delete a message that does not exist.
This is happening because you are using an unreliable syntax for finding the channels. #get was changed in V12, I would use #find.
To combat this, you should use
await message.guild.channels.fetch(); //fetches all channels
const channel = client.channels.cache.find(channel => channel.id === "<id here>");
To make sure you search through all channels, use an await message.guild.channels.fetch()
Here is the changelog for V12
Below is my code.I am unable resolve the o/p.How to resolve in async and await.I am trying to get data from other collection and pass it to existing filtered collection
exports.listStatus = async (root, { _id, start, limit }) => {
var user = await db.User.find({ _id: _id })
let list = user[0].savedUsers
var blocked = user[0].blockedUsers
var listAll = list.push(_id)
let listOfStatus = await db.Status.find({ userId: { $in: list }, reportStatus: { $ne: _id }, _id: { $nin: blocked } });
let array;
let leng = listOfStatus.length
let statusCommentsArray
var arrayStatus = [];
listOfStatus.forEach((status, key) => {
let promise = new Promise((resolve, reject) => {
var obj = {}
var statusId = status._id
var listOfLiked = status.like
let likeCount = listOfLiked.length
var sortedList = listOfLiked.sort({ createdDate: -1 })
obj.likeCount = likeCount
db.Comment.find({ statusId: statusId }, (err, statusCommentsList) => {
var statusCommentsCount = statusCommentsList.length
var sortedList = statusCommentsList.sort({ createdDate: -1 })
if (statusCommentsCount >= 3) {
statusCommentsArray = sortedList
}
else {
statusCommentsArray = sortedList.slice(0, 3)
}
obj.statusCommentsCount = statusCommentsCount
obj.statusCommentsArray = statusCommentsArray
arrayStatus.push(obj)
leng--;
if (leng == 0) {
resolve(arrayStatus)
}
})
})
promise.then((response) => {
return Promise.resolve(response)
})
})
}
forgive me the question.
I'm not used to node and sync / await
I have the following function which queries a mongodb returning a json, I'm saving that return on redis.
So far so good.
findLightnings: async (request, h) => {
const q = request.query.q.split(':');
const index = q[0];
const value = q[1].split(',');
const dateInit = new Date(request.query.dateInit);
const dateEnd = new Date(request.query.dateEnd);
const page = request.query.page;
const distance = request.query.distance;
const redis = require('redis');
const client = redis.createClient();
let limit = 300;
let filter = {
$and: [{
data: {
$gte: dateInit.toISOString(),
$lte: dateEnd.toISOString()
}
}]
}
if (index === 'latlng') {
filter['$and'][0]['geo.coordinates'] = {
$near: {
$geometry: {
type: 'Point',
coordinates: value.map(Number),
$minDistance: 0,
$maxDistance: distance
}
}
}
limit = 100;
} else {
filter['$and'][0][`cidade.${index}`] = {
$in: value
}
}
return client.get('elektro', async (err, reply) => {
let resp = null;
if (reply) {
console.log(reply); //<<<<<<<< Return Json OK
resp = reply // <<<<<<<<<< Return TRUE in json's place
} else {
console.log('db')
const query = await Lightning.find(filter).sort('data').skip(page*limit).limit(limit).exec();
client.set('elektro', JSON.stringify(query));
client.expire('elektro', 3600);
resp = query
}
return JSON.stringify(resp);
})
}
The problem is time to recover this data from the redis.
In the console log json appears normal, how much tento returns that value for the main function it comes 'TRUE' and not the json saved in redis.
Someone can give me a helping hand on this.
I really need this function.
const redis = require('redis');
const client = redis.createClient(6379);
const bluebird = require("bluebird");
bluebird.promisifyAll(redis.RedisClient.prototype);
bluebird.promisifyAll(redis.Multi.prototype);
const redisdata = await client.getAsync("user:photos");
if (redisdata) {
console.log(`cache EXISTS`)
return res.json({ source: 'cache', data: JSON.parse(redisdata) })
}
I was able to solve the problem with the redis client.getAsync().
which already has a native async function:
source: Node-redis
The final code is as follows:
findLightnings: async (request, h) => {
const q = request.query.q.split(':');
const index = q[0];
const value = q[1].split(',');
const dateInit = new Date(request.query.dateInit);
const dateEnd = new Date(request.query.dateEnd);
const page = request.query.page;
const distance = request.query.distance;
let limit = 300;
let filter = {
$and: [{
data: {
$gte: dateInit.toISOString(),
$lte: dateEnd.toISOString()
}
}]
}
if (index === 'latlng') {
filter['$and'][0]['geo.coordinates'] = {
$near: {
$geometry: {
type: 'Point',
coordinates: value.map(Number),
$minDistance: 0,
$maxDistance: distance
}
}
}
limit = 100;
} else {
filter['$and'][0][`cidade.${index}`] = {
$in: value
}
}
return getAsync('findLightnings'+ '/' + request.query.q + '/' + request.query.dateInit + '/' + request.query.dateEnd).then(async (res) => {
if(res){
console.log('Fonte Dados => redis')
return res
}else{
console.log('Fonte Dados => db')
try {
const query = await Lightning.find(filter).sort('data').exec();//.skip(page*limit).limit(limit).exec();
client.set('findLightnings'+ '/' + request.query.q + '/' + request.query.dateInit + '/' + request.query.dateEnd, JSON.stringify(query));
return query;
} catch (err) {
return Boom.badData(err);
}
}
client.close();
});
},