Creating a Custom Data Adapter: Importing data adapter - autodesk-forge

Following the tutorial for creating a custom data adapter:
https://forge.autodesk.com/en/docs/dataviz/v1/developers_guide/advanced_topics/custom_data_adapter/
Getting error in chrome console:
Created file Hyperion.Data.BimapiDataAdapter in the folder forge-dataviz-iot-reference-app-main\node_modules\forge-dataviz-iot-data-modules\client\data based on the Hyperion.Data.Adapter file in the same folder. Then edited on line 371 and changed RestApiDataAdapter to BimapiDataAdapter.
Then trying to import this in BaseApp.jsx on line 34 in the folder forge-dataviz-iot-reference-app-main\node_modules\forge-dataviz-iot-react-components\client\components.

Your Hyperion.Data.BimapiDataAdapter.js is not placed aside forge-dataviz-iot-react-components/BaseApp.jsx, so the package-tool Webpack cannot it by ./Hyperion.Data.BimapiDataAdapter in BaseApp.jsx.
Here is my approach to exposing Hyperion.Data.BimapiDataAdapter.js.
Create Hyperion.Data.BimapiDataAdapter.js under forge-dataviz-iot-reference-app-main\node_modules\forge-dataviz-iot-data-modules\client\data. Here is how it looks like (just copied and pasted the contents of RestApiDataAdapter for the quick demo)
import { DataAdapter } from './Hyperion.Data';
/**
* Data adapter class dealing with sample data.
* #memberof Autodesk.DataVisualization.Data
* #alias Autodesk.DataVisualization.Data.BimapiDataAdapter
* #augments DataAdapter
*/
export class BimapiDataAdapter extends DataAdapter {
/**
* Constructs an instance of BimapiDataAdapter.
*/
constructor(provider = "synthetic", baseName = "") {
super("BimapiDataAdapter", baseName);
/* eslint-disable no-undef */
this._provider = provider;
}
/**
* Loads all DeviceModel objects from the sample REST API.
*
* #returns {Promise<DeviceModel[]>} A promise that resolves to a single
* dimensional array containing a list of loaded DeviceModel objects. If no
* DeviceModel is available, the promise resolves to an empty array.
* #memberof Autodesk.DataVisualization.Data
* #alias Autodesk.DataVisualization.Data.BimapiDataAdapter#loadDeviceModels
*/
async loadDeviceModels() {
const adapterId = this.id;
return fetch(this._getResourceUrl("api/device-models"))
.then((response) => response.json())
.then((rawDeviceModels) => {
/** #type {DeviceModel[]} */
const normalizedDeviceModels = [];
rawDeviceModels.forEach((rdm) => {
// Create a normalized device model representation.
const ndm = new DeviceModel(rdm.deviceModelId, adapterId);
ndm.name = rdm.deviceModelName;
ndm.description = rdm.deviceModelDesc;
// Generate device property representation.
rdm.deviceProperties.forEach((rdp) => {
const propId = rdp.propertyId;
const propName = rdp.propertyName;
const ndp = ndm.addProperty(propId, propName);
ndp.description = rdp.propertyDesc;
ndp.dataType = rdp.propertyType;
ndp.dataUnit = rdp.propertyUnit;
ndp.rangeMin = rdp.rangeMin ? rdp.rangeMin : undefined;
ndp.rangeMax = rdp.rangeMax ? rdp.rangeMax : undefined;
});
normalizedDeviceModels.push(ndm);
});
// Fetch actual devices for each of the device models.
return this.fetchDevicesForModels(normalizedDeviceModels);
});
}
/**
* Fetches actual device IDs and populate DeviceModel objects with them.
*
* #param {DeviceModel[]} deviceModels The DeviceModel objects for which
* actual device IDs are to be populated.
*
* #returns {Promise<DeviceModel[]>} A promise that resolves to the
* DeviceModel objects populated with actual device IDs.
* #memberof Autodesk.DataVisualization.Data
* #alias Autodesk.DataVisualization.Data.BimapiDataAdapter#fetchDevicesForModels
*/
async fetchDevicesForModels(deviceModels) {
const promises = deviceModels.map((deviceModel) => {
const model = deviceModel.id;
return fetch(this._getResourceUrl("api/devices", { model: model }))
.then((response) => response.json())
.then((jsonData) => jsonData.deviceInfo);
});
return Promise.all(promises).then((deviceInfosList) => {
// Assign devices to each device model.
deviceModels.forEach((deviceModel, index) => {
// Turn data provider specific device data format into
// the unified data format stored in Device object.
//
const deviceInfos = deviceInfosList[index];
deviceInfos.forEach((deviceInfo) => {
const device = deviceModel.addDevice(deviceInfo.id);
device.name = deviceInfo.name;
const p = deviceInfo.position;
device.position = new THREE.Vector3(
parseFloat(p.x),
parseFloat(p.y),
parseFloat(p.z)
);
device.lastActivityTime = deviceInfo.lastActivityTime;
device.deviceModel = deviceModel;
device.sensorTypes = deviceModel.propertyIds;
});
});
return deviceModels;
});
}
/**
* Fetches the property data based on the given device ID.
*
* #param {QueryParam} query Parameters of this query.
*
* #returns {Promise<DeviceData>} A promise that resolves to an aggregated
* property data for the queried device.
* #memberof Autodesk.DataVisualization.Data
* #alias Autodesk.DataVisualization.Data.BimapiDataAdapter#fetchDeviceData
*/
async fetchDeviceData(query) {
const pids = query.propertyIds;
const promises = pids.map((pid) => this._fetchPropertyData(query, pid));
return Promise.all(promises).then((deviceDataList) => {
const deviceData = new DeviceData(query.deviceId);
deviceDataList.forEach((devData) => deviceData.mergeFrom(devData));
return deviceData;
});
}
/**
* Fetches data for a single property based on the given device ID.
*
* #param {QueryParam} query Parameters of this query.
* #param {string} propertyId The ID of the property.
*
* #returns {Promise<DeviceData>} A promise that resolves to an aggregated
* property data for the queried device.
*/
async _fetchPropertyData(query, propertyId) {
const url = this._getResourceUrl("api/aggregates", {
device: query.deviceId,
property: propertyId,
startTime: query.dateTimeSpan.startSecond,
endTime: query.dateTimeSpan.endSecond,
resolution: query.dateTimeSpan.resolution,
});
return fetch(url)
.then((response) => response.json())
.then((rawAggregates) => {
// Convert 'rawAggregates' which is in the following format, into 'AggregatedValues'
//
// rawAggregates = {
// timestamps: number[],
// count: number[],
// min: number[],
// max: number[],
// avg: number[],
// sum: number[],
// stdDev: number[]
// }
//
const aggrValues = new AggregatedValues(query.dateTimeSpan);
aggrValues.tsValues = rawAggregates.timestamps;
aggrValues.countValues = rawAggregates.count;
aggrValues.maxValues = rawAggregates.max;
aggrValues.minValues = rawAggregates.min;
aggrValues.avgValues = rawAggregates.avg;
aggrValues.sumValues = rawAggregates.sum;
aggrValues.stdDevValues = rawAggregates.stdDev;
aggrValues.setDataRange("avgValues", getPaddedRange(aggrValues.avgValues));
const deviceData = new DeviceData(query.deviceId);
const propertyData = deviceData.getPropertyData(propertyId);
propertyData.setAggregatedValues(aggrValues);
return deviceData;
})
.catch((err) => {
console.error(err);
});
}
/**
* Gets the resource URL for a given endpoint with query parameters
*
* #param {string} endpoint The endpoint for the URL to generate
* #param {Object.<string, string>} parameters Key-value pairs of query parameters
*
* #returns {string} The string that represents the complete resource URL
* #private
*/
_getResourceUrl(endpoint, parameters) {
parameters = parameters || {};
parameters["provider"] = this._provider;
parameters["project"] = "unused";
const ps = Object.entries(parameters).map(([k, v]) => `${k}=${v}`);
return `${this._baseName}/${endpoint}?${ps.join("&")}`;
}
}
Expose the class BimapiDataAdapter from ``forge-dataviz-iot-reference-app-main\node_modules\forge-dataviz-iot-data-modules\client.js`
export * from "./client/data/Hyperion.Data";
export * from "./client/data/Hyperion.Data.BimapiDataAdapter"; //!<<< add this line
Import BimapiDataAdapter in forge-dataviz-iot-reference-app-main\node_modules\forge-dataviz-iot-react-components\client\components\BaseApp.jsx from where import { ... } from "forge-dataviz-iot-data-modules/client" is
import {
Session,
AzureDataAdapter,
RestApiDataAdapter,
DataView,
DateTimeSpan,
EventType,
DeviceProperty,
DeviceModel,
BimapiDataAdapter //!<<< here it is
} from "forge-dataviz-iot-data-modules/client";
Afterward, re-execute ENV=local npm run dev in your terminal console.
If you have further questions on how Webpack resolves packages, I would advise you to check these out:
https://webpack.js.org/concepts/module-resolution/
https://webpack.js.org/concepts/module-federation/

Related

Exponential Backoff test only tries once

Trying to test an Exponential Backoff function, but it only appears to Catch once then return. I'm sure it's something simple, but what am I missing?
EB fn
function tryAgain(action, maxTries = 5) {
for (let tries = 0; tries < maxTries; tries++) {
Logger.log(`Try number ${tries}`);
try {
return action();
} catch (e) {
Logger.log(`Error caught; trying again: ${e}`);
if (tries = maxTries) { throw e; };
}
Utilities.sleep(2 ** tries * 1000)
}
}
test fn
function myFunction() {
tryAgain(testTryAgain);
}
function testTryAgain() {
Logger.log("test");
throw "error msg"
}
Use a more reliable exponential backoff implementation, like this:
function myFunction() {
exponentialBackoff_(testTryAgain);
}
To supply arguments, use a closure, like this:
function myFunction() {
const param = 1;
const result = exponentialBackoff_(() => testTryAgain(param));
console.log(result);
}
Here is a copy of the exponentialBackoff_() function from Exception: Failed to retrieve form data, including full JSDoc and attribution:
/**
* Calls a closure, retries on failure, and returns the value it gives.
*
* Usage:
* exponentialBackoff_(myFunction);
* // ...or:
* exponentialBackoff_(() => myFunction(param1, param2));
* // ...or:
* const result = exponentialBackoff_(() => myFunction(param1, param2));
* // ...or:
* const respondentEmail = exponentialBackoff_(() => e.response.getRespondentEmail());
*
* #see https://en.wikipedia.org/wiki/Exponential_backoff
* #param {Function} action The closure to call.
* #param {Number} maxNumTries Optional. The number of times to retry. Defaults to 5.
* #return {Object} The closure return value.
*/
function exponentialBackoff_(action, maxNumTries = 5) {
// version 1.0, written by --Hyde, 29 December 2022
// - see https://stackoverflow.com/a/74952372/13045193
for (let tryNumber = 1; tryNumber <= maxNumTries; tryNumber++) {
try {
return action();
} catch (error) {
if (tryNumber >= maxNumTries) {
throw error;
}
Utilities.sleep(2 ** (tryNumber - 1) * 1000);
}
}
}

Need an appropriate loader to handle this file type. | * #type {import(‘../../ipfs/src/core/components/add-all’).AddAll<import(‘.’).HttpOptions>}

I downloaded source code from GitHub and try to run it.
It ran but then came the issue with “ipfs-api” so then I install the latest version of “iphs-http-client” now it pops up a lot of error relating to
PLEASE TELL ME IF THIS CAN BE SOLVE IF CANT TELL ME THE REASON TOO, I'm new to this
error in ./node_modules/ipfs-http-client/src/add-all.js
Module parse failed: C:\Users\lione\Sample\Document-verification-on-Blockchain\node_modules\ipfs-http-client\src\add-all.js Unexpected token (16:17)
You may need an appropriate loader to handle this file type.
| * #type {import('../../ipfs/src/core/components/add-all').AddAll<import('.').HttpOptions>}
| */
| async function * addAll (input, options = {}) {
| const progressFn = options.progress
|
# ./node_modules/ipfs-http-client/src/index.js 32:12-32
# ./ethereum/ipfs.js
# ./pages/Org/show.js?entry
# multi ./pages/Org/show.js?entry
this is the error log
add-all.js
'use strict'
const CID = require('cids')
const toCamel = require('./lib/object-to-camel')
const configure = require('./lib/configure')
const multipartRequest = require('./lib/multipart-request')
const toUrlSearchParams = require('./lib/to-url-search-params')
const anySignal = require('any-signal')
const AbortController = require('abort-controller').default
module.exports = configure((api) => {
// eslint-disable-next-line valid-jsdoc
/**
* #type {import('../../ipfs/src/core/components/add-all').AddAll<import('.').HttpOptions>}
*/
async function * addAll (input, options = {}) {
const progressFn = options.progress
// allow aborting requests on body errors
const controller = new AbortController()
const signal = anySignal([controller.signal, options.signal])
const res = await api.post('add', {
searchParams: toUrlSearchParams({
'stream-channels': true,
...options,
progress: Boolean(progressFn)
}),
timeout: options.timeout,
signal,
...(
await multipartRequest(input, controller, options.headers)
)
})
for await (let file of res.ndjson()) {
file = toCamel(file)
if (file.hash !== undefined) {
yield toCoreInterface(file)
} else if (progressFn) {
progressFn(file.bytes || 0)
}
}
}
return addAll
})
/**
* #typedef {import('../../ipfs/src/core/components/add-all').UnixFSEntry} UnixFSEntry
*/
/**
* #returns {UnixFSEntry}
*/
function toCoreInterface ({ name, hash, size, mode, mtime, mtimeNsecs }) {
const output = {
path: name,
cid: new CID(hash),
size: parseInt(size)
}
if (mode != null) {
output.mode = parseInt(mode, 8)
}
if (mtime != null) {
output.mtime = {
secs: mtime,
nsecs: mtimeNsecs || 0
}
}
// #ts-ignore
return output
}
index.js
'use strict'
/* eslint-env browser */
const CID = require('cids')
const multiaddr = require('multiaddr')
const multibase = require('multibase')
const multicodec = require('multicodec')
const multihash = require('multihashes')
const globSource = require('ipfs-utils/src/files/glob-source')
const urlSource = require('ipfs-utils/src/files/url-source')
/**
* #typedef { import("./lib/core").ClientOptions } ClientOptions
*/
/**
* #typedef {object} HttpOptions
* #property {Headers | Record<string, string>} [headers] - An object or [Headers](https://developer.mozilla.org/en-US/docs/Web/API/Headers) instance that can be used to set custom HTTP headers. Note that this option can also be [configured globally](#custom-headers) via the constructor options.
* #property {URLSearchParams | Record<string, string>} [searchParams] - An object or [`URLSearchParams`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams) instance that can be used to add additional query parameters to the query string sent with each request.
* #property {object} [ipld]
* #property {any[]} [ipld.formats] - An array of additional [IPLD formats](https://github.com/ipld/interface-ipld-format) to support
* #property {(format: string) => Promise<any>} [ipld.loadFormat] - an async function that takes the name of an [IPLD format](https://github.com/ipld/interface-ipld-format) as a string and should return the implementation of that codec
*/
// eslint-disable-next-line valid-jsdoc
/**
* #param {ClientOptions} options
*/
function ipfsClient (options = {}) {
return {
add: require('./add')(options),
addAll: require('./add-all')(options),
bitswap: require('./bitswap')(options),
block: require('./block')(options),
bootstrap: require('./bootstrap')(options),
cat: require('./cat')(options),
commands: require('./commands')(options),
config: require('./config')(options),
dag: require('./dag')(options),
dht: require('./dht')(options),
diag: require('./diag')(options),
dns: require('./dns')(options),
files: require('./files')(options),
get: require('./get')(options),
getEndpointConfig: require('./get-endpoint-config')(options),
id: require('./id')(options),
key: require('./key')(options),
log: require('./log')(options),
ls: require('./ls')(options),
mount: require('./mount')(options),
name: require('./name')(options),
object: require('./object')(options),
pin: require('./pin')(options),
ping: require('./ping')(options),
pubsub: require('./pubsub')(options),
refs: require('./refs')(options),
repo: require('./repo')(options),
resolve: require('./resolve')(options),
stats: require('./stats')(options),
stop: require('./stop')(options),
shutdown: require('./stop')(options),
swarm: require('./swarm')(options),
version: require('./version')(options)
}
}
Object.assign(ipfsClient, { CID, multiaddr, multibase, multicodec, multihash, globSource, urlSource })
module.exports = ipfsClient
It looks like you're using babel via webpack to transpile the source code and it's failing to parse the async generator function syntax. You may need to add a plugin or otherwise fix your config.

Laravel Notifications Base Table not found

I am working on a Laravel project. I ran these commands and successfully created notifications table.
php artisan notifications:table
php artisan migrate
All of the things were going perfectly. Later on I created a Model name "NotificationsForAdmin" with migration named "notifications_for_admin", then later on I drooped this table. Now when I am trying to generate some notifications then it is showing me this error, I dont know whats going on I have notifications table in database that is needed for laravel notifications with perfect schema. the error is :
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'followup.notification_for_admins' doesn't exist (SQL: select * from `notification_for_admins` where `notification_for_admins`.`user_id` = 2 and `notification_for_admins`.`user_id` is not null)
My notifications is :
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use App\User;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\BroadcastMessage;
use Illuminate\Notifications\Messages\MailMessage;
use App\Events\NewEmailReceivedEvent;
use Auth;
class NewEmailReceived extends Notification
{
use Queueable;
public $sender_id, $receiver_id, $sender_name, $receiver_name, $sender_type, $receiver_type, $type, $recipient, $from_email, $subject, $message, $image, $receiver_image, $attachments, $sizesOfAttachments, $originalFileNames, $thread_id, $id_of_email;
/**
* Create a new notification instance.
*
* #return void
*/
public function __construct($sender_id, $receiver_id, $sender_name, $receiver_name, $sender_type, $receiver_type, $type, $recipient, $from_email, $subject, $message, $image, $receiver_image, $attachments, $sizesOfAttachments, $originalFileNames, $thread_id, $id_of_email)
{
$this->sender_id = $sender_id;
$this->receiver_id = $receiver_id;
$this->sender_name = $sender_name;
$this->receiver_name = $receiver_name;
$this->sender_type = $sender_type;
$this->receiver_type = $receiver_type;
$this->type = $type;
$this->recipient = $recipient;
$this->from_email = $from_email;
$this->subject = $subject;
$this->message = $message;
$this->image = $image;
$this->receiver_image = $receiver_image;
$this->attachments = $attachments;
$this->sizesOfAttachments = $sizesOfAttachments;
$this->originalFileNames = $originalFileNames;
$this->thread_id = $thread_id;
$this->id_of_email = $id_of_email;
}
/**
* Get the notification's delivery channels.
*
* #param mixed $notifiable
* #return array
*/
public function via($notifiable)
{
$notifications = Auth::user()->notifications;
if ($notifications[7]->shown == 1) {
return ['mail', 'database'];
}
else{
return ['database'];
}
}
/**
* Get the array representation of the notification.
*
* #param mixed $notifiable
* #return array
*/
public function toDatabase($notifiable)
{
return [
'sender_id' => $this->sender_id,
'receiver_id' => $this->receiver_id,
'sender_name' => $this->sender_name,
'receiver_name' => $this->receiver_name,
'sender_type' => $this->sender_type,
'receiver_type' => $this->receiver_type,
'type' => $this->type,
'recipient' => $this->recipient,
'from_email' => $this->from_email,
'subject' => $this->subject,
'message' => $this->message,
'image' => $this->image,
'receiver_image' => $this->receiver_image,
'attachments' => $this->attachments,
'sizesOfAttachments' => $this->sizesOfAttachments,
'originalFileNames' => $this->originalFileNames,
'thread_id' => $this->thread_id,
'id_of_email' => $this->id_of_email,
];
event(new NewEmailReceivedEvent($NewEmailReceivedRequest));
return $NewEmailReceivedRequest;
}
/**
* Get the mail representation of the notification.
*
* #param mixed $notifiable
* #return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
return (new MailMessage)
->subject("New email from ".$this->sender_type)
->greeting('Hello!')
->markdown('mails.NewEmailReceived' , ['recipient_name' => $this->receiver_name , 'subject' => $this->subject , 'mailMessage' => str_limit($this->message, 50) , 'avatar' => $this->image]);
}
/**
* Get the array representation of the notification.
*
* #param mixed $notifiable
* #return array
*/
public function toArray($notifiable)
{
return [
//
];
}
}
I shall be very thankfull if someone could help me on this.
It seems your notifications relation on your User object still references NotificationsForAdmin.
If you do not specify the table for a model, the table is automatically generated as a snake_case string of the model name. In the case of NotificationsForAdmin this becomes notification_for_admins.
Add the public property $table to your NotificationsForAdmin with the name of the table where your notifications are stored as the value. This should fix your problem.

Laravel Echo / Pusher authentication fails (403)

Learning Laravel event broadcasting / Echo / Vue and playing around with this tutorial.
I keep getting 403 responses to authentication, and I suspect my lack of understanding on the channels.php routes is the issue. I am using Player model instead of User for Auth which works ok.
Event ChatMessageSend
class ChatMessageSent implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $channel;
public $player;
public $chatMessage;
/**
* Create a new event instance.
* GameChat constructor.
* #param $chatMessage
* #param $player
*/
public function __construct(ChatMessage $chatMessage, Player $player)
{
$this->channel = session()->get('chat.channel');
$this->chatMessage = $chatMessage;
$this->player = $player;
}
/**
* Get the channels the event should broadcast on.
*
* #return Channel|array
*/
public function broadcastOn()
{
return new PrivateChannel($this->channel);
}
}
Listener ChatMessageNotification (default / empty)
class ChatMessageNotification
{
/**
* ChatMessageNotification constructor.
*/
public function __construct()
{
//
}
/**
* Handle the event.
*
* #param ChatMessageSent $event
* #return void
*/
public function handle(ChatMessageSent $event)
{
//
}
}
Controller ChatController
class ChatController extends Controller
{
/**
* Send chat message
*
* #param Request $request
* #return \Illuminate\Database\Eloquent\Collection|static[]
*/
public function getMessages(Request $request)
{
return ChatMessage::with('player')
->where('progress_id', '=', session('game.progress.id'))
->orderBy('created_at', 'DESC')
->get();
}
/**
* Send chat message
*
* #param Request $request
* #return array|string
*/
public function sendMessage(Request $request)
{
$player = Auth::user();
$message = $request->input('message');
if ($message) {
$message = ChatMessage::create([
'player_id' => $player->id,
'progress_id' => session()->get('game.progress.id'),
'message' => $request->input('message')
]);
}
broadcast(new ChatMessageSent($player, $message))->toOthers();
return ['type' => 'success'];
}
}
Routes channels.php
Broadcast::channel(session()->get('chat.channel'), function ($player, $message) {
return $player->inRoom();
});
And in my Player class
/**
* A user can be in one chat channel
*/
public function inRoom()
{
if ((Auth::check()) and ($this->games()->where('progress_id', '=', session('game.progress.id'))->get())) {
return true;
}
return false;
}
When a player logs in, I store in session a chat room id which I would like to use as channel.
My vue chat instance is
Vue.component('chat-messages', require('./../generic/chat-messages.vue'));
Vue.component('chat-form', require('./../generic/chat-form.vue'));
const app = new Vue({
el: '#toolbar-chat',
data: {
messages: []
},
created() {
this.fetchMessages();
Echo.private(chat_channel)
.listen('chatmessagesent', (e) => {
this.messages.unshift({
message: e.data.message,
player: e.data.player.nickname
});
});
},
methods: {
fetchMessages() {
axios.get(chat_get_route)
.then(response => {
this.messages = response.data;
});
},
addMessage(message) {
this.messages.unshift(message);
this.$nextTick(() => {
this.$refs.toolbarChat.scrollTop = 0;
});
axios.post(chat_send_route, message)
.then(response => {
console.log(response.data);
});
}
}
});
But I keep getting
POST http://my-games.app/broadcasting/auth 403 (Forbidden)
Pusher : Couldn't get auth info from your webapp : 403
Error 403 /broadcasting/auth with Laravel version > 5.3 & Pusher, you need change your code in resources/assets/js/bootstrap.js with
window.Echo = new Echo({
broadcaster: 'pusher',
key: 'your key',
cluster: 'your cluster',
encrypted: true,
auth: {
headers: {
Authorization: 'Bearer ' + YourTokenLogin
},
},
});
And in app/Providers/BroadcastServiceProvider.php change by
Broadcast::routes()
with
Broadcast::routes(['middleware' => ['auth:api']]);
or
Broadcast::routes(['middleware' => ['jwt.auth']]); //if you use JWT
it worked for me, and hope it help you.
It may be an idea to figure out whether your routes/channels.php file is doing as you expect. Maybe add some logging to see if that route gets called at all, and that your inRoom function is returning what you expect.
In case anyone still needs an answer, this worked for me.
Add to your broadcastServiceProvider.php
Broadcast::routes([
'middleware' => 'auth:api']);
add to your channels.php
Broadcast::channel('chat', function () {
return Auth::check();
});

Converting the Inline Json Data to Remote Json File

I used the answer at : YUI 3 -Datatable with Paginator + Query Builder + Sort tried
to for the samples http://jsbin.com/iwijek/10 and http://jsfiddle.net/UwjUt/ which have inline json data. I wanted to parse the remote json file for which I used the .get() as per YUI 3 docs. But bit does not do anything. plz check these examples and help me in parsing the remote json file.
{ var url = "file:///e:/Documents/json-search.txt";
var modelList;
dataSource = new Y.DataSource.Get({ source: url });
// comment
// var modelList = new Y.ModelList();
modelList = new Y.ModelList.Get({
source: url });
modelList.add();
}
json-search.txt
[{
name : 'Joe Bloggs',
company : 'ABC Inc',
state : 'AZ',
cost : 100
},
{
name : 'Jane Mary',
company : 'Bits and Bobs Ltd',
state : 'TX',
cost : 1000
},
{
name : 'Paul Smith',
company : 'PS Clothing PLC',
state : 'TX',
cost :400
},
{
name : 'Jack Jones',
company : 'jackjones.com',
State : 'NY',
cost: 9999
},
{
name : 'Crazy Horse',
company : 'Wacky Places Ltd.',
state : 'MI',
cost : 632
}]
I also tried to pass the datasource to the ModelList
YUI.add(
'datatable-filter',
function(Y) {
/**
Adds support for filtering the table data by API methods
#module datatable
#submodule datatable-filter
#since 3.5.0
**/
var YLang = Y.Lang,
isBoolean = YLang.isBoolean,
isString = YLang.isString,
isArray = YLang.isArray,
isObject = YLang.isObject,
toArray = Y.Array,
sub = YLang.sub;
/**
<pre><code>
var table = new Y.DataTable({
columns: [ 'id', 'username', 'name', 'birthdate' ],
data: [ ... ],
filters: true // this will render a filter input box for every column
});
table.render('#table');
</code></pre>
Setting `filters` to `true` will enable UI filtering for all columns. To enable
UI filtering for certain columns only, set `filters` to an array of column keys,
or just add `filters: true` to the respective column configuration objects.
This uses the default setting of `filters: auto` for the DataTable instance.
<pre><code>
var table = new Y.DataTable({
columns: [
'id',
{ key: 'username', renderFilter: true },
{ key: 'name' },
{ key: 'birthdate', renderFilter: true, filter : "=123", filterFn : customFilterFn }
],
data: [ ... ]
// filters: 'auto' is the default
});
To disable UI filtering for all columns, set `filters` to `false`. This still
permits filtering via the API methods.
filter via api:
var filterBy =
{
username : "=student",
name : "%richard",
birthdate : ">01-01-1975"
}
table.set("filterBy",filterBy);
As new records are inserted into the table's `data` ModelList, they will be checked against the filter to determine if they will be rendered
The current filters are stored in the `filterBy` attribute. Assigning this value at instantiation will automatically filter your data.
Filtering is done by a simple value comparison using '=', '!=', '<', '<=', '>', '>=' on the field value.
If you need custom filtering, add a filter function in the column's `filterFn` property. // TODO...
<pre><code>
function applePiesFilter(a) {
return a.get("type") == 'apple' ? true : false;
}
var table = new Y.DataTable({
columns: [ 'id', 'username', { key: name, filterFn: nameFilter }, 'birthdate' ],
data: [ ... ],
filters: [ 'username', 'name', 'birthdate' ]
});
</code></pre>
See the user guide for more details.
#class DataTable.Filters
#for DataTable
#since 3.5.0
**/
function Filters() {}
Filters.ATTRS = {
// Which columns in the UI should suggest and respond to filtering interaction
// pass an empty array if no UI columns should show filters, but you want the
// table.filter(...) API
/**
Controls which columns can show a filtering input
Acceptable values are:
* "auto" - (default) looks for `renderFilter: true` in the column configurations
* "true" - all columns have a filter field rendered
* "false" - no UI filters are enabled
* {String[]} - array of key names to give filter fields
#attribute filters
#type {String|String[]|Boolean}
#default "auto"
#since 3.5.0
**/
filters: {
value: 'auto',
validator: '_validateFilters'
},
/**
The current filter configuration to maintain in the data.
Accepts column `key` objects with a single property the value of the filter
E.g. `{ username: '%student' }`
E.g. `[{ username : '%student' }, { age : '<40'}]
#attribute filterBy
#type {String|String[]|Object|Object[]}
#since 3.5.0
**/
filterBy: {
validator: '_validateFilterBy'
},
/**
Strings containing language for filtering tooltips.
#attribute strings
#type {Object}
#default (strings for current lang configured in the YUI instance config)
#since 3.5.0
**/
strings: {}
};
Y.mix(Filters.prototype, {
/**
Filter the data in the `data` ModelList and refresh the table with the new
order.
#method filter
#param {String|String[]|Object|Object[]} fields The field(s) to filter by
#param {Object} [payload] Extra `filter` event payload you want to send along
#return {DataTable}
#chainable
#since 3.5.0
**/
filter : function (fields, payload) {
/**
Notifies of an impending filter, either from changing the filter in the UI
header, or from a call to the `filter` method.
The requested filter is available in the `filterBy` property of the event.
The default behavior of this event sets the table's `filterBy` attribute.
#event filter
#param {String|String[]|Object|Object[]} filterBy The requested filter
#preventable _defFilterFn
**/
return this.fire('filter', Y.merge((payload || {}), {
filterBy: fields || this.get('filterBy')
}));
},
/**
Template for the row that will hold the filter inputs
#property FILTERS_HEADER_CELL_TEMPLATE
#type {HTML}
#value
**/
FILTERS_HEADER_ROW_TEMPLATE : '<tr class="{filterRowClassName}" tabindex="0"></tr>',
/**
Template for the row that will hold the filter inputs
#property FILTERS_HEADER_CELL_TEMPLATE
#type {HTML}
#value
//<select><option value="=">=</option><option value="%">%</option><option value="!=">!=</option><option value="!%">!%</option><option value=">">%gt</option><option value=">=">>=</option><option value="<"><</option><option value="<="><=</option></select>
**/
FILTERS_HEADER_CELL_TEMPLATE : '<th class="{className}" tabindex="0" rowspan="1" colspan="1" title="Filter by {colName}">' +
'<div class="{linerClass}" tabindex="0"><input type="text" data-yui3-col-key="{colKey}" class="{inputClass}"/></div></th>',
/**
Template for the row that will doesn't have filter inputs
#property FILTERS_HEADER_CELL_TEMPLATE_NONE
#type {HTML}
#value
**/
FILTERS_HEADER_CELL_TEMPLATE_NONE : '<th class="{className}" tabindex="0" rowspan="1" colspan="1" title="Filtering unavailable on this field"></th>',
//--------------------------------------------------------------------------
// Protected properties and methods
//--------------------------------------------------------------------------
/**
Filters the `data` ModelList based on the new `filterBy` configuration.
#method _afterFilterByChange
#param {EventFacade} e The `filterByChange` event
#protected
#since 3.5.0
**/
_afterFilterByChange: function (e) {
var filters;
// Can't use a setter because it's a chicken and egg problem. The
// columns need to be set up to translate, but columns are initialized
// from Core's initializer. So construction-time assignment would
// fail.
// WHAT DOES THIS MEAN??
this._setFilterBy();
if (this._filterBy.length) {
// build the filter function
this._buildFilterFn();
// get the filtered data
this._filteredData = this.data.filter( { asList : true }, this._filterFn);
} else {
this._filteredData = this.data;
}
// 'hide' the filtered rows
this._hideFilteredData();
},
/**
#description if the row is not in the filtered data hide it, otherwise show it
#method _hideFilteredData
#protected
#since 3.5.0
**/
_hideFilteredData: function () {
var i,len,clientId;
for(i=0, len = this.data.size(); this._filteredData.getById && i < len; ++i) {
clientId = this.data.item(i).get("clientId");
if(this._filteredData.getByClientId(clientId)) {
this.get("contentBox").one("tbody").one("[data-yui3-record=" + clientId + "]").setStyle("display","table-row");
} else {
this.get("contentBox").one("tbody").one("[data-yui3-record=" + clientId + "]").setStyle("display","none");
}
}
},
/**
Applies the filtering logic to the new ModelList if the `newVal` is a new
ModelList.
#method _afterFilterDataChange
#param {EventFacade} e the `dataChange` event
#protected
#since 3.5.0
**/
_afterFilterDataChange: function (e) {
// object values always trigger a change event, but we only want to
// call _initFilterFn if the value passed to the `data` attribute was a
// new ModelList, not a set of new data as an array, or even the same
// ModelList.
if (e.prevVal !== e.newVal || e.newVal.hasOwnProperty('_compare')) {
// this._initFilterFn();
}
},
/**
Checks if any of the fields in the modified record are fields that are
currently being filtered by, and if so, refilters the `data` ModelList.
#method _afterFilterRecordChange
#param {EventFacade} e The Model's `change` event
#protected
#since 3.5.0
**/
_afterFilterRecordChange: function (e) {
var i, len;
for (i = 0, len = this._filterBy.length; i < len; ++i) {
if (e.changed[this._filterBy[i].key]) {
this.data.filter();
break;
}
}
},
/**
Subscribes to state changes that warrant updating the UI, and adds the
click handler for triggering the filter operation from the UI.
#method _bindFilterUI
#protected
#since 3.5.0
**/
_bindFilterUI: function () {
var handles = this._eventHandles;
// 'filterByChange' -> need to update UI
if (!handles.filterAttrs) {
handles.filterAttrs = this.after(
['filtersChange', 'columnsChange'],
Y.bind('_uiSetFilters', this));
}
if (!handles.filterUITrigger && this._theadNode) {
handles.filterUITrigger = this.delegate(['keyup','blur'],
Y.rbind('_onUITriggerFilter', this),
'.' + this.getClassName('filter', 'input'));
}
},
/**
Sets the `filterBy` attribute from the `filter` event's `e.filterBy` value.
#method _defFilterFn
#param {EventFacade} e The `filter` event
#protected
#since 3.5.0
**/
_defFilterFn: function (e) {
this.set.apply(this, ['filterBy', e.filterBy].concat(e.details));
},
/**
Sets up the initial filter state and instance properties. Publishes events
and subscribes to attribute change events to maintain internal state.
#method initializer
#protected
#since 3.5.0
**/
initializer: function () {
var boundParseFilter = Y.bind('_parseFilter', this);
this._parseFilter();
this._setFilterBy();
this._initFilterStrings();
// dataChange : Y.bind('_afterFilterDataChange', this),
//
// filterChange : boundParseFilter
this.after({
'sort' : this._hideFilteredData,
'columnsChange' : boundParseFilter,
'filterByChange' : Y.bind('_afterFilterByChange', this),
'table:renderHeader': Y.bind('_renderFilters', this)});
// this.data.after(this.data.model.NAME + ":change",
// Y.bind('_afterFilterRecordChange', this));
// TODO: this event needs magic, allowing async remote filtering
// this.publish('filter', {
// defaultFn: Y.bind('_defFilterFn', this)
// });
},
/**
Add the filter related strings to the `strings` map.
#method _initFilterStrings
#protected
#since 3.5.0
**/
_initFilterStrings: function () {
// Not a valueFn because other class extensions will want to add to it
this.set('strings', Y.mix((this.get('strings') || {}),
Y.Intl.get('datatable-filter')));
},
/**
#description Fires the `filter` event in response to user changing the UI filters
#method _onUITriggerFilter
#param {DOMEventFacade} e The `mouseout` event
#protected
#since 3.5.0
**/
_onUITriggerFilter: function (e) {
var colKey = e.currentTarget.getAttribute('data-yui3-col-key'),
column = colKey && this.getColumn(colKey),
filterBy = this.get("filterBy") || {},
i, len;
e.halt(); // not doing anything anyway?
if (column) {
filterBy[colKey] = e.currentTarget.get("value");
}
this.set("filterBy",filterBy);
},
/**
#description Build the filter function from the column config, this function is passed to the model list fiter() method
#method _buildFilterFn
#protected
#since 3.5.0
**/
_buildFilterFn: function () {
var i,len,op1,op2, key, filter, filterFn;
filterFn = function(model,index,modelList) {
var key,filter,op1,op2,val,filter,passesFilter = true;
for(i=0,len = this._filterBy.length; i< len && passesFilter; ++i) {
key = this._filterBy[i].key;
filter = this._filterBy[i].filter;
val = model.get(key) || '';
op1 = filter.substr(0,1);
op2 = filter.substr(1,1);
if(op2 == '=') {
switch(op1) {
case '!':
// not equal
if(val.toLowerCase() == filter.substr(2).toLowerCase()) {
passesFilter = false;
}
break;
case '>':
// greater or equal
if(parseInt(val) < parseInt(filter.substr(2))) {
passesFilter = false;
}
break;
case '<':
// less than or equal
if(parseInt(val) > parseInt(filter.substr(2))) {
passesFilter = false;
}
break;
}
} else if (op2 == '%' && op1 =='!') {
// not like
if((val.toLowerCase().indexOf(filter.substr(2).toLowerCase()) > -1)) {
passesFilter = false;
}
break;
} else {
switch(op1) {
case '=':
// equal
if(val.toLowerCase() != filter.substr(1).toLowerCase()) {
passesFilter = false;
}
break;
case '>':
// greater than
if(parseInt(val) <= parseInt(filter.substr(1))) {
passesFilter = false;
}
break;
case '<':
// less than
if(parseInt(val) >= parseInt(filter.substr(1))) {
passesFilter = false;
}
break;
case '%':
// like
if((val.toLowerCase().indexOf(filter.substr(1).toLowerCase()) === -1)) {
passesFilter = false;
}
break;
default:
// consider to be like
if((String(val).toLowerCase().indexOf(String(filter).toLowerCase()) === -1)) {
passesFilter = false;
}
break;
}
}
}
return passesFilter;
};
this._filterFn = Y.bind(filterFn,this);
},
/**
#description Normalizes the possible input values for the `filter` attribute setting up the column config as appropriate
#method _parseFilter
#protected
#since 3.5.0
**/
_parseFilter: function () {
var filters = this.get('filters'),
columns = [],
i, len, col;
col = this._displayColumns.slice();
this._uiFilters = false;
if(filters === 'auto') {
// look for key on columns
col = this._displayColumns.slice();
for(i = 0; i < col.length; i++) {
if(col[i].renderFilter) {
this._uiFilters = true;
}
}
} else if(filters === true) {
// provide UI filters for all cols
col = this._displayColumns.slice();
for(i = 0; i < col.length; i++) {
this._uiFilters = true;
this._displayColumns[i].renderFilter = true;
}
} else if (isArray(filters)) {
// provide UI filters on the specified cols (plural)
for (i = 0, len=filters.length; i < len; ++i) {
if(col = this.getColumn(filters[i])) {
this._uiFilters = true;
col.renderFilter = true;
}
}
} else if (filters) {
// provide UI filter on the specifed 'COL' (singular)
for (i = 0, len = col.length; i < len; ++i) {
if (col[i].key === filters) {
this._uiFilters = true;
this._displayColumns[i].renderFilter = true;
i = len;
}
}
}
},
/**
Initial application of the filters UI.
#method _renderFilters
#protected
#since 3.5.0
**/
_renderFilters: function () {
this._uiSetFilters();
this._bindFilterUI();
},
/**
#description Parses the current `filterBy` attribute and updates the columns
#method _setFilterBy
#protected
#since 3.5.0
**/
_setFilterBy: function () {
var columns = this._displayColumns,
filterBy = this.get('filterBy') || {},
filteredClass = ' ' + this.getClassName('filtered'),
i, len, name, dir, field, column;
this._filterBy = [];
// Purge current filter state from column configs
for (i = 0, len = columns.length; i < len; ++i) {
column = columns[i];
delete columns[i].filter;
if (column.className) {
// TODO: be more thorough
column.className = column.className.replace(filteredClass, '');
}
}
for (key in filterBy) {
if(filterBy[key]!='') {
// Allow filtering of any model field and any column
column = this.getColumn(key) || { _id: key, key: key };
if (column) {
column.filter = filterBy[key];
if (!column.className) {
column.className = '';
}
column.className += filteredClass;
this._filterBy.push(column);
}
}
}
},
/**
Array of column configuration objects of those columns that need UI setup
for user interaction.
#property _filters
#type {Object[]}
#protected
#since 3.5.0
**/
//_filters: null,
/**
Array of column configuration objects for those columns that are currently
being used to filter the data. Fake column objects are used for fields that
are not rendered as columns.
#property _filterBy
#type {Object[]}
#protected
#since 3.5.0
**/
//_filterBy: null,
/**
Replacement `comparator` for the `data` ModelList that defers filtering logic
to the `_compare` method. The deferral is accomplished by returning `this`.
#method _filterComparator
#param {Model} item The record being evaluated for filter position
#return {Model} The record
#protected
#since 3.5.0
**/
_filterComparator: function (item) {
// Defer filtering to ModelList's _compare
return item;
},
/**
Applies the appropriate classes to the `boundingBox` and column headers to
indicate filter state and filterability.
Also currently wraps the header content of filters columns in a `<div>`
liner to give a CSS anchor for filter indicators.
#method _uiSetFilters
#protected
#since 3.5.0
**/
_uiSetFilters: function () {
var columns = this._displayColumns.slice(),
filtersClass = this.getClassName('filters', 'column'),
filtersHidden = this.getClassName("filters","hidden"),
filterRowClass = this.getClassName("filters","row"),
filteredClass = this.getClassName('filtered'),
linerClass = this.getClassName('filter', 'liner'),
i, len, col, node, liner, title, desc;
this.get('boundingBox').toggleClass(
this.getClassName('filters'),
columns.length);
/// NEED TO ADDRESS
if((node = this._theadNode.one("." + filterRowClass))) {
node.remove(true);
}
if(columns.length>0 && this._uiFilters) {
tr = this._theadNode.appendChild(Y.Lang.sub(
this.FILTERS_HEADER_ROW_TEMPLATE, {
filterRowClassName: filterRowClass }));
for (i = 0, len = columns.length; i < len; ++i) {
if(columns[i].renderFilter) {
tr.append(Y.Lang.sub(
this.FILTERS_HEADER_CELL_TEMPLATE, {
className: this.getClassName("filter","cell"),
colKey : columns[i].key,
colName : columns[i].label || columns[i].key,
inputClass : this.getClassName("filter","input"),
linerClass: linerClass
}));
} else {
tr.append(Y.Lang.sub(
this.FILTERS_HEADER_CELL_TEMPLATE_NONE, {
className: this.getClassName("no-filter")
}));
}
}
}
},
/**
Allows values `true`, `false`, "auto", or arrays of column names through.
#method _validateFilters
#param {Any} val The input value to `set("filters", VAL)`
#return {Boolean}
#protected
#since 3.5.0
**/
_validateFilters: function (val) {
return val === 'auto' || isBoolean(val) || isArray(val);
},
/**
Allows strings, arrays of strings, objects, or arrays of objects.
#method _validateFilterBy
#param {String|String[]|Object|Object[]} val The new `filterBy` value
#return {Boolean}
#protected
#since 3.5.0
**/
_validateFilterBy: function (val) {
return val;
return val === null ||
isString(val) ||
isObject(val, true) ||
(isArray(val) && (isString(val[0]) || isObject(val, true)));
}
}, true);
Y.DataTable.Filters = Filters;
Y.Base.mix(Y.DataTable, [Filters]);
},"0.1", {
requires : []});
YUI().use('datatable-sort','datatable-filter',function(Y) {
// comment
//var modelList = new Y.ModelList();
var url = "file:///e:/Documents/json-search.txt";
var modelList, datasource;
modelList = new Y.ModelList();
datasource = Y.DataSource.IO({ source: "file:///e:/Documents/json-search.txt" });
modelList.plug(Y.Plugin.ModelListDataSource, {
source : datasource, });
datasource.sendRequest();
var dataTable = new Y.DataTable (
{
columns : [ {key:"name",label:"Person",renderFilter:true,filter:"Joe"},"company",{key:"state",renderFilter:true},{key:"cost",renderFilter:true}],
data : modelList, sortable : true, filters : 'auto'
}).render("#table");
modelList.item(1).set("id",102);
Y.one("#showhidefilters").on("click",function(e) {e.halt();Y.one("#table").one(".yui3-datatable-filters-row").toggleClass("yui3-datatable-filters-hidden");});
});