I am trying to connect to the websocket using django and I'm still getting same connection error. I've checked the documents and using the same code from the tutorial.
const jobSocket = new WebSocket(
"ws{% if request.get_host != 'localhost:8000' %}s{% endif %}://" + window.location.host + "/ws/jobs/{{ job.id }}/"
);
// Execute this function whenever this page receives an event from Job Consumer via WebSocket
jobSocket.onmessage = function (e) {
var data = JSON.parse(e.data);
var job = data.job;
console.log(job);
l've tried using routing.py and asgi.py to access the path but the error is still the same "raise ValueError("No route found for path %r." % path)
ValueError: No route found for path 'ws/jobs/c5d1cc51-c2ad-458e-9cc7-f62520009112/'."
I've tried different url patterns, different regrex esspresion and no luck.
I tried this create a wair function to see if the websocket would open but it never does.
function waitForSocketConnection(socket, callback){
setTimeout(
function () {
if (socket.readyState === 1) {
console.log("Connection is made")
if (callback != null){
callback();
}
} else {
console.log("wait for connection...")
waitForSocketConnection(socket, callback);
}
}, 10); // wait 5 milisecond for the connection...
}
function updateCourierPosition(map) {
let url = `ws://${window.location.host}/ws/jobs/{{ job.id }}/`
const jobSocket = new WebSocket(url)
waitForSocketConnection(jobSocket,function() {
jobSocket.onopen = function(event){
jobSocket.send("connect")
console.log("connect");
};
})
asgi.py
application = ProtocolTypeRouter(
{
"http": django_asgi_app,
"websocket": AllowedHostsOriginValidator(
AuthMiddlewareStack(URLRouter(websocket_urlpatterns))
),
}
)
urls.py
websocket_urlpatterns = [
path('ws/jobs/<job_id>', consumers.JobConsumer.as_asgi()),
]
consumer.py
class JobConsumer(AsyncWebsocketConsumer):
def connect(self):
self.job_id = self.scope['url_route']['kwargs']['job_id']
self.job_group_name = 'job_%s' % self.job_id
# Join room group
async_to_sync(self.channel_layer.group_add)(
self.job_group_name,
self.channel_name
)
self.accept()
async def disconnect(self, close_code):
# Leave room group
await self.channel_layer.group_discard(self.group_name, self.channel_name)
async def receive(self, text_data):
text_data_json = json.loads(text_data)
job = text_data_json['job']
print("Job", job)
Any help or assistance is appreciated.
Related
I am trying for a day now and cannot solve this problem:
I have a website where I can add contacts to a SQLite database. I want to query the database by studentID or nachname (this means last name). I have an API endpoint which seems to be working and a getContact function which only works for the first parameter. In this case it only searches for studentID and if I change the order I can only get my data by nachname.
For now I just want to display the response simply at the URL localhost:8000/api/contacts/studentID or /nachname to see the json response.
I tried this getContact function:
async getContact(**studentID, nachname**) { //here only the first parameter works
let result = [];
let query;
let params = [];
if (studentID && !nachname) {
query = "SELECT * FROM contacts WHERE studentID = ?";
params.push(studentID);
} else if (nachname && !studentID) {
query = "SELECT * FROM contacts WHERE nachname = ?";
params.push(nachname);
} else if (studentID && nachname) {
query = "SELECT * FROM contacts WHERE studentID = ? OR nachname = ?";
params.push(studentID, nachname);
}
result = await new Promise((resolve, reject) => {
db.all(query, params, (error, row) => {
if (error) {
reject(error);
} else {
resolve(row);
}
});
});
return result;
}
My API endpoint (setup with Express.js in Node.js) looks like this currently:
app
.get("/api/contacts/:studentID?/:nachname?", async (request, response) => {
const studentID = request.params.studentID;
const nachname = request.params.nachname;
console.log(request.params.studentID);
console.log(request.params.nachname);
const contact = await contactsManager.getContact(studentID, nachname);
if (contact) {
response.status(200).send(contact);
} else {
response.status(404);
}
})
I don't understand why the getContact function only works with the first parameter.
One strange thing I recognized: Right now I could search for localhost:8000/api/contacts/1 and would see the right entry, and when I add .../contacts/1/Behrens I see the entry with the ID 1 and also the entries of the people named Behrens. Maybe this information helps?
The issue is that in your getContact function, you are using the ** operator in front of studentID and nachname, which is causing them to be treated as keyword arguments instead of regular arguments. As a result, the function is only able to identify and use the first argument passed to it, while the second argument is ignored.
To fix this, you should remove the ** operator from the function definition so that the function takes in two regular arguments:
async getContact(studentID, nachname) {
// ...
}
Also, you can use SELECT * FROM contacts WHERE studentID = ? AND nachname = ? instead of SELECT * FROM contacts WHERE studentID = ? OR nachname = ? if you want to check the both parameter are exist in the database.
Also, you should check for the existence of the parameters in the API endpoint before passing them to the getContact function, otherwise, you may end up passing undefined values to the function which will cause an error.
app.get("/api/contacts/:studentID?/:nachname?", async (request, response) => {
let studentID = request.params.studentID;
let nachname = request.params.nachname;
if(!studentID) studentID = null;
if(!nachname) nachname = null;
console.log(studentID);
console.log(nachname);
const contact = await contactsManager.getContact(studentID, nachname);
if (contact) {
response.status(200).send(contact);
} else {
response.status(404);
}
})
Also, you can use only one parameter in the endpoint and use if-else statements to check which parameter is passed and then act accordingly in the function.
app.get("/api/contacts/:param?", async (request, response) => {
let studentID = request.params.param;
let nachname = request.params.param;
if(studentID.match(/^\d+$/)){
studentID = request.params.param;
nachname = null;
}else{
studentID = null;
nachname = request.params.param;
}
console.log(studentID);
console.log(nachname);
const contact = await contactsManager.getContact(studentID, nachname);
if (contact) {
response.status(200).send(contact);
} else {
response.status(404);
}
})
This should fix the issue with the getContact function only working with the first parameter, and allow you to query the database by both studentID and nachname.
I am making a discord bot (Here is the original one) in javascript of my GTA V RP server, the bot has a command that tells you the name, id and ping of the players but when there are more than 25 players an error occurs ( RangeError: RichEmbeds may not exceed 25 fields.). I have thought about the idea of having more than 25 players send the others in another message.
Here´s the code:
exports.run = async (client, message, args) => {
var util = require("../fivem");
message.delete();
if (servers[message.guild.id].guild === message.guild.id) {
try {
var arg = `${servers[message.guild.id].ip}`
/* var args = `${servers[message.guild.id].ip}` */
let api = `http://${arg}/players.json`
let api2 = `http://${arg}/info.json`
/* if (!args) {return util.embed("Please Specify a Direct-IP address ex: `"+config.prefix+"players thatziv.ddns.net:30120`")}
if (!message.content.includes(":")) {return util.embed("Please Specify a port ex: **"+config.prefix+"players thatziv.ddns.net__:30120__**")} */
req(api2, function (err, response, main) {
req(api, function (err, response, body) {
if (err) {
util.zembed("That server is offline or does not exist... \n**Console:**\n```js\n" + err + "```")
}
else {
try {
var start = JSON.parse(body)
var start2 = JSON.parse(main)
if (start == null || start == []) {
var e = 0
} else {
var e = start.length;
}
var embed = new Discord.RichEmbed()
.setColor(color)
.setAuthor(state, icon)
.setThumbnail(icon)
.setDescription(`__**FamousLifeRP Players**__\n(First 25 players)\n**${e}** out of **${start2.vars.sv_maxClients}** Players.`)
start.forEach(function (element) {
var sv = `**${element.name}**\nID: **${element.id}** Ping: **${element.ping}**`;
embed.addField(`**${element.name}**`, `ID: **${element.id}** Ping: **${element.ping}**`)
})
message.channel.send({ embed: embed });
log(`Used Command [PLAYERS] in ${message.guild.name}`)
} catch (err) {
util.embed("That server is offline or does not exist...\n**Console:**\n```js\n" + err + "```")
}
}
})
})
} catch (err) {
util.embed("That server does not exist. \n**Console:**\n```js\n" + err + "```");
}
} else {
return util.embed("Please **set** a Direct-Address for this server. ex: `" + config.prefix + "set thatziv.ddns.net:30120`\n***__Please make sure to include the address with port.__***")
}
};
var exampleJSON = [
{
"endpoint": "[::ffff:5.15.226.104]:27594",
"id": 294,
"identifiers": [
"steam:110000114ff0dc9",
"license:12eaf8ef61955729188ff56b08e820c8a61bcbc3",
"ip:5.15.226.104"
],
"name": "Leonadro Di la Londra",
"ping": 165
}
]
And here´s the error:
"That server is offline or does not exist...
Console:
RangeError: RichEmbeds may not exceed 25 fields."
create an array of embeds, loop through your array. Use a counter inside the loop. Add fields to the embed as normal. Once counter hits 25, push a new embed object into the array of embeds, then redirect your new fields to the newly added embed. Repeat until you finish adding all fields. Then you can send all of the embeds to the channel.
(might wanna watch out for message ratelimit if you have a ton of data)
I'm not going to write all the code for you but it should look something like this:
const embeds = [];
let counter = 0;
start.forEach(e => {
if(!embeds[Math.floor(counter/25)]) { //checks if the embed exists in array
embeds.push(new Discord.MessageEmbed();
//add embed, do whatever you need to title, etc. here
}
embeds[Math.floor(counter/25)].addField("",""); // whatever you need to add
counter++;
}
embeds.forEach(e => {
message.channel.send(e);
//might watch out for this too because they dont send synchronously
//you could try Promise.all or something
}
Another thing to note is that your code snippet seems to be using a deprecated version of Discord.js, please use the latest version (12.5.1)
This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 3 years ago.
I am trying to basically call the 'get' method from html/ejs when a button is pressed to query the database and display the results. Sorry if it's very simple, but I just can't get it work.
I tried to require the file and call the function inside a script tag but that doesn't work on the browser. I tried to add the js file with a <script src="text/javascript" src="filename"> but that also results in errors.
The rest API I built talks to oracle 11g (Toad) using oracledb.
I am basically trying to call the get function in this class
const employees = require('../db_apis/employees.js');
async function get(req, res, next) {
try {
const context = {};
context.id = parseInt(req.params.id, 10);
const rows = await employees.find(context);
if (req.params.id) {
if (rows.length === 1) {
res.status(200).json(rows[0]);
} else {
res.status(404).end();
}
} else {
res.status(200).json(rows);
}
} catch (err) {
next(err);
}
}
...
db_apis/employees.js
const oracledb = require('oracledb');
const database = require('../services/database');
async function find(context) {
const baseQuery =
`SELECT *
FROM choice_names`;
console.log('in find');
let query = baseQuery;
const binds = {};
let additionalQuery = '\nwhere ';
if (context.id) {
binds.choice_name = context.id;
additionalQuery += `choice_name = :choice_name`;
// query += `\nwhere choice_name = :choice_name`;
} else if (context.user) {
binds.choice_user = context.user;
additionalQuery += `choice_user = :choice_user`;
} else if (context.date) {
binds.choice_date = context.date;
additionalQuery += `choice_date = :choice_date`;
}
if (context.id || context.user || context.date) {
query += additionalQuery;
}
console.log(query);
const result = await database.simpleExecute(query, binds);
return result.rows;
}
...
router.js
const express = require('express');
const router = new express.Router();
const employees = require('../controllers/employees');
router.route('/employees/:id?')
.get(employees.get)
.post(employees.post)
.put(employees.put)
.delete(employees.delete);
module.exports = router;
index.ejs
...
<button onclick="get()">Click me</button>
...
You are (very)confusing frontend and backend code.
The express app is in backend, running on some port, exposing the /employees/:id route.
But the frontend part doesn't have access to the backend scripts, So you need to do a XHR(Ajax) request from frontend to that route and get the result.
For example, in jQuery it can be something as
function get(){
$.get('/employees/1').done(..do something..)
}
You can refer this answer on how to do it on angular.
I'm currently working on a Alexa Skill for my Smart Home.
I created a Lambda function and want to make a http request to a server. but it wont execute any of my anon. functions.
A lambda code example:
/* This code has been generated from your interaction model by skillinator.io
/* eslint-disable func-names */
/* eslint quote-props: ["error", "consistent"]*/
// There are three sections, Text Strings, Skill Code, and Helper Function(s).
// You can copy and paste the contents as the code for a new Lambda function, using the alexa-skill-kit-sdk-factskill template.
// This code includes helper functions for compatibility with versions of the SDK prior to 1.0.9, which includes the dialog directives.
// 1. Text strings =====================================================================================================
// Modify these strings and messages to change the behavior of your Lambda function
const request = require("request");
let speechOutput;
let reprompt;
let welcomeOutput = "Hallo xyz!";
let welcomeReprompt = "xy";
// 2. Skill Code =======================================================================================================
"use strict";
const Alexa = require('alexa-sdk');
const APP_ID = "my id"; // TODO replace with your app ID (OPTIONAL).
speechOutput = '';
const handlers = {
'LaunchRequest': function () {
this.emit(':ask', welcomeOutput, welcomeReprompt);
},
'AMAZON.HelpIntent': function () {
speechOutput = 'Placeholder response for AMAZON.HelpIntent.';
reprompt = '';
this.emit(':ask', speechOutput, reprompt);
},
'AMAZON.CancelIntent': function () {
speechOutput = 'Placeholder response for AMAZON.CancelIntent';
this.emit(':tell', speechOutput);
},
'AMAZON.StopIntent': function () {
speechOutput = 'Placeholder response for AMAZON.StopIntent.';
this.emit(':tell', speechOutput);
},
'SessionEndedRequest': function () {
speechOutput = '';
//this.emit(':saveState', true);//uncomment to save attributes to db on session end
this.emit(':tell', speechOutput);
},
'LichtIntent': function () {
//delegate to Alexa to collect all the required slot values
let filledSlots = delegateSlotCollection.call(this);
speechOutput = '';
//any intent slot variables are listed here for convenience
let zimmerSlotRaw = this.event.request.intent.slots.zimmer.value;
console.log(zimmerSlotRaw);
let zimmerSlot = resolveCanonical(this.event.request.intent.slots.zimmer);
console.log(zimmerSlot);
let was_lichtSlotRaw = this.event.request.intent.slots.was_licht.value;
console.log(was_lichtSlotRaw);
let was_lichtSlot = resolveCanonical(this.event.request.intent.slots.was_licht);
console.log(was_lichtSlot);
//THIS IS THE PART WHERE I NEED HELP!!
MakeRequest(function(data){
console.log("asddd");
speechOutput = "This is a place holder response for the intent named LichtIntent, which includes dialogs. This intent has 2 slots, which are zimmer, and was_licht. Anything else?";
var speechOutput = data;
this.emit(':ask', speechOutput, speechOutput);
});
console.log("asdww");
//DOWN TO HERE!!
},
'StromIntent': function () {
//delegate to Alexa to collect all the required slot values
let filledSlots = delegateSlotCollection.call(this);
speechOutput = '';
//any intent slot variables are listed here for convenience
let geraet_stromSlotRaw = this.event.request.intent.slots.geraet_strom.value;
console.log(geraet_stromSlotRaw);
let geraet_stromSlot = resolveCanonical(this.event.request.intent.slots.geraet_strom);
console.log(geraet_stromSlot);
let wasSlotRaw = this.event.request.intent.slots.was.value;
console.log(wasSlotRaw);
let wasSlot = resolveCanonical(this.event.request.intent.slots.was);
console.log(wasSlot);
//Your custom intent handling goes here
speechOutput = "This is a place holder response for the intent named StromIntent, which includes dialogs. This intent has 2 slots, which are geraet_strom, and was. Anything else?";
this.emit(':ask', speechOutput, speechOutput);
},
'FrageIntent': function () {
//delegate to Alexa to collect all the required slot values
let filledSlots = delegateSlotCollection.call(this);
speechOutput = '';
//any intent slot variables are listed here for convenience
let geraetSlotRaw = this.event.request.intent.slots.geraet.value;
console.log(geraetSlotRaw);
let geraetSlot = resolveCanonical(this.event.request.intent.slots.geraet);
console.log(geraetSlot);
let was_frageSlotRaw = this.event.request.intent.slots.was_frage.value;
console.log(was_frageSlotRaw);
let was_frageSlot = resolveCanonical(this.event.request.intent.slots.was_frage);
console.log(was_frageSlot);
//Your custom intent handling goes here
speechOutput = "This is a place holder response for the intent named FrageIntent, which includes dialogs. This intent has 2 slots, which are geraet, and was_frage. Anything else?";
this.emit(':ask', speechOutput, speechOutput);
},
'TuerIntent': function () {
//delegate to Alexa to collect all the required slot values
let filledSlots = delegateSlotCollection.call(this);
speechOutput = '';
//any intent slot variables are listed here for convenience
let zeitSlotRaw = this.event.request.intent.slots.zeit.value;
console.log(zeitSlotRaw);
let zeitSlot = resolveCanonical(this.event.request.intent.slots.zeit);
console.log(zeitSlot);
//Your custom intent handling goes here
speechOutput = "This is a place holder response for the intent named TuerIntent, which includes dialogs. This intent has one slot, which is zeit. Anything else?";
this.emit(':ask', speechOutput, speechOutput);
},
'Unhandled': function () {
speechOutput = "The skill didn't quite understand what you wanted. Do you want to try something else?";
this.emit(':ask', speechOutput, speechOutput);
}
};
exports.handler = (event, context) => {
const alexa = Alexa.handler(event, context);
alexa.appId = APP_ID;
// To enable string internationalization (i18n) features, set a resources object.
//alexa.resources = languageStrings;
alexa.registerHandlers(handlers);
//alexa.dynamoDBTableName = 'DYNAMODB_TABLE_NAME'; //uncomment this line to save attributes to DB
alexa.execute();
};
// END of Intent Handlers {} ========================================================================================
// 3. Helper Function =================================================================================================
//THESE ARE MY HELPER FUNCTIONS
function url(){
console.log("asd");
return " my server ip";
}
function MakeRequest(callback){
console.log("hallo!");
request.get(url(), function(error, response, body){
console.log("****************************************");
console.log(response);
console.log("****************************************");
console.log(error);
console.log("****************************************");
console.log(body);
console.log("****************************************");
callback("erfolg!");
});
console.log("hffggh");
}
//DOWN TO HERE!!
function resolveCanonical(slot){
//this function looks at the entity resolution part of request and returns the slot value if a synonyms is provided
let canonical;
try{
canonical = slot.resolutions.resolutionsPerAuthority[0].values[0].value.name;
}catch(err){
console.log(err.message);
canonical = slot.value;
};
return canonical;
};
function delegateSlotCollection(){
console.log("in delegateSlotCollection");
console.log("current dialogState: "+this.event.request.dialogState);
if (this.event.request.dialogState === "STARTED") {
console.log("in Beginning");
let updatedIntent= null;
// updatedIntent=this.event.request.intent;
//optionally pre-fill slots: update the intent object with slot values for which
//you have defaults, then return Dialog.Delegate with this updated intent
// in the updatedIntent property
//this.emit(":delegate", updatedIntent); //uncomment this is using ASK SDK 1.0.9 or newer
//this code is necessary if using ASK SDK versions prior to 1.0.9
if(this.isOverridden()) {
return;
}
this.handler.response = buildSpeechletResponse({
sessionAttributes: this.attributes,
directives: getDialogDirectives('Dialog.Delegate', updatedIntent, null),
shouldEndSession: false
});
this.emit(':responseReady', updatedIntent);
} else if (this.event.request.dialogState !== "COMPLETED") {
console.log("in not completed");
// return a Dialog.Delegate directive with no updatedIntent property.
//this.emit(":delegate"); //uncomment this is using ASK SDK 1.0.9 or newer
//this code necessary is using ASK SDK versions prior to 1.0.9
if(this.isOverridden()) {
return;
}
this.handler.response = buildSpeechletResponse({
sessionAttributes: this.attributes,
directives: getDialogDirectives('Dialog.Delegate', null, null),
shouldEndSession: false
});
this.emit(':responseReady');
} else {
console.log("in completed");
console.log("returning: "+ JSON.stringify(this.event.request.intent));
// Dialog is now complete and all required slots should be filled,
// so call your normal intent handler.
return this.event.request.intent;
}
}
function randomPhrase(array) {
// the argument is an array [] of words or phrases
let i = 0;
i = Math.floor(Math.random() * array.length);
return(array[i]);
}
function isSlotValid(request, slotName){
let slot = request.intent.slots[slotName];
//console.log("request = "+JSON.stringify(request)); //uncomment if you want to see the request
let slotValue;
//if we have a slot, get the text and store it into speechOutput
if (slot && slot.value) {
//we have a value in the slot
slotValue = slot.value.toLowerCase();
return slotValue;
} else {
//we didn't get a value in the slot.
return false;
}
}
//These functions are here to allow dialog directives to work with SDK versions prior to 1.0.9
//will be removed once Lambda templates are updated with the latest SDK
function createSpeechObject(optionsParam) {
if (optionsParam && optionsParam.type === 'SSML') {
return {
type: optionsParam.type,
ssml: optionsParam['speech']
};
} else {
return {
type: optionsParam.type || 'PlainText',
text: optionsParam['speech'] || optionsParam
};
}
}
function buildSpeechletResponse(options) {
let alexaResponse = {
shouldEndSession: options.shouldEndSession
};
if (options.output) {
alexaResponse.outputSpeech = createSpeechObject(options.output);
}
if (options.reprompt) {
alexaResponse.reprompt = {
outputSpeech: createSpeechObject(options.reprompt)
};
}
if (options.directives) {
alexaResponse.directives = options.directives;
}
if (options.cardTitle && options.cardContent) {
alexaResponse.card = {
type: 'Simple',
title: options.cardTitle,
content: options.cardContent
};
if(options.cardImage && (options.cardImage.smallImageUrl || options.cardImage.largeImageUrl)) {
alexaResponse.card.type = 'Standard';
alexaResponse.card['image'] = {};
delete alexaResponse.card.content;
alexaResponse.card.text = options.cardContent;
if(options.cardImage.smallImageUrl) {
alexaResponse.card.image['smallImageUrl'] = options.cardImage.smallImageUrl;
}
if(options.cardImage.largeImageUrl) {
alexaResponse.card.image['largeImageUrl'] = options.cardImage.largeImageUrl;
}
}
} else if (options.cardType === 'LinkAccount') {
alexaResponse.card = {
type: 'LinkAccount'
};
} else if (options.cardType === 'AskForPermissionsConsent') {
alexaResponse.card = {
type: 'AskForPermissionsConsent',
permissions: options.permissions
};
}
let returnResult = {
version: '1.0',
response: alexaResponse
};
if (options.sessionAttributes) {
returnResult.sessionAttributes = options.sessionAttributes;
}
return returnResult;
}
function getDialogDirectives(dialogType, updatedIntent, slotName) {
let directive = {
type: dialogType
};
if (dialogType === 'Dialog.ElicitSlot') {
directive.slotToElicit = slotName;
} else if (dialogType === 'Dialog.ConfirmSlot') {
directive.slotToConfirm = slotName;
}
if (updatedIntent) {
directive.updatedIntent = updatedIntent;
}
return [directive];
}
I use the "request" module for my http-request, I think you all know this module.
When I test my function, it gives me NO runtime error!
but the anonymous functions from the MakeRequest call and the request.get call wont execute, and I don't know why.
For Example the console output:
Hallo!,
Asd (very funny.. it gets the params for the request.get.. the bug has to be between the second param(the anon function itself?) in the call and the start of the anon function),
hffggh,
asdww
-the console.logs in the anon. functions doesn't show.
I maybe undestand why the MakeRequest funct. doesn't run -> because the callback from it never came. But why does the request.get not work?? I pasted the necessary parts (the MakeRequest and the helper functions) in a normal node projekt, and it worked!!? -facepalm.... im nearly crying..
My Goal: I want to receive a response from the server.. - thats all. But it just wont go into the function where I can access the response object(s).
(Scroll down to the helper functions)
Please help me out guys, I could really hit my head against the wall.
Reguards
In an imaginary Session module as bellow, could the _sessData variable be leaked in between request. For instance maybe a user just logged in, and at a "same time" a isAuthed() called is made for a different user. Could this be a problem? This module would be called on every request so I guess it's safe but a confirmation would be great.
module.exports = function(app) {
var _sessData = null;
function Session() {
//
}
Session.prototype.set = function( payload ) {
Cookies.set('session', payload);
_sessData = payload;
}
Session.prototype.isAuthed = function() {
return _sessData && Object.keys(_sessData).length > 0;
}
Session.prototype.clear = function() {
Cookies.set('session', '');
_sessData = {};
}
Object.defineProperty(app.context, 'Session', {
// Not exaclty sure what is happening here with this and _ctx..
// Note: apprently ctx is bound to the middleware when call()ing
get: function() { return new Session(this); }
});
return function * (next) {
var token = Cookies.get('jwt');
if ( ! token ) {
_sessData = {};
return yield* next;
}
try {
_sessData = jwt.verify(token, SECRET);
} catch(e) {
if (e.name === 'TokenExpiredError') {
this.Session.clear();
}
}
yield* next;
}
}
EDIT:
The module get used in a KoaJS app like so (the above module does not produce a proper KoaJS middleware but this is beside the point):
var app = require('koa')();
// JWT session middleware
var session = require("./session")();
app.use(session);
app.listen(3080);
What you are exporting is a function, so _sessData does not actually exist when you import the module. It gets created when you call the function. Each time the function is called -- and it needs to be called once per request -- a new variable in that scope with the name _sessData is created. No, they cannot interfere with each other.