How can I seperate functions which are basically the same but use different states? Vue2/Vuex - vue.js

Ive got a problem since i realized that I break the DRY(Dont repeat yourself) rule. So basically I have 2 modules(movies, cinemas) and few methods in them which look the same but use their module' state.
Example: Movies has 'movies' state. Cinemas has 'cinemas' state.
//cinemas.ts
#Mutation
deleteCinemaFromStore(id: string): void {
const cinemaIndex = this.cinemas.findIndex((item) => item.id === id);
if (cinemaIndex >= 0) {
const cinemasCopy = this.cinemas.map((obj) => {
return { ...obj };
});
cinemasCopy.splice(cinemaIndex, 1);
this.cinemas = cinemasCopy;
} else {
throw new Error("Provided id doesn't exist");
}
}
//movies.ts
#Mutation
deleteMovieFromStore(id: string): void {
const movieIndex = this.movies.findIndex((item) => item.id === id);
if (movieIndex >= 0) {
const moviesCopy = this.movies.map((obj) => {
return { ...obj };
});
moviesCopy.splice(movieIndex, 1);
this.movies = moviesCopy;
} else {
throw new Error("Provided id doesn't exist");
}
}
My struggle is: How can I seperate these methods into utils.ts if they have reference to 2 different states?

define another function that take the id, state and store context (this) as parameters :
function delete(id:string,itemsName:string,self:any){
const itemIndex= self[itemsName].findIndex((item) => item.id === id);
if (itemIndex>= 0) {
const itemsCopy = self[itemsName].map((obj) => {
return { ...obj };
});
itemsCopy.splice(itemIndex, 1);
self[itemsName] = itemsCopy;
} else {
throw new Error("Provided id doesn't exist");
}
}
then use it like :
//cities.ts
#Mutation
deleteCityFromStore(id: string): void {
delete(id,'cities',this)
}
//countries.ts
#Mutation
deleteCountryFromStore(id: string): void {
delete(id,'countries',this)
}

Related

Validator not validating the request in Laravel 8

I am inserting the data. The data is being entering quite fine but whenever I enter a letter the entry is done but that entry is converted to '0'.
This is my controller store function:
public function store(GuidanceReportRequest $request)
{
$stats = GuidanceReport::where('user_id', $request->user_id)->whereDate('created_at', now())->count();
if ($stats > 0) {
Session::flash('warning', 'Record already exists for current date');
return redirect()->route('reports.index');
}
if ((!empty($request->call_per_day[0]) && !empty($request->transfer_per_day[0])) ||
(!empty($request->call_per_day[1]) && !empty($request->transfer_per_day[1])) || (!empty($request->call_per_day[2])
&& !empty($request->transfer_per_day[2]))
) {
foreach ($request->category as $key => $value) {
$catgeory_id = $request->category[$key];
$call_per_day = $request->call_per_day[$key];
$transfer_per_day = $request->transfer_per_day[$key];
if (!empty($catgeory_id) && !empty($call_per_day) && !empty($transfer_per_day)) {
GuidanceReport::create([
"user_id" => $request->user_id,
"categories_id" => $catgeory_id,
"call_per_day" => $call_per_day,
"transfer_per_day" => $transfer_per_day,
]);
}
}
} else {
GuidanceReport::create($request->except('category', 'call_per_day', 'transfer_per_day'));
}
Session::flash('success', 'Data Added successfully!');
return redirect()->route('reports.index');
}
This is my Validation Request code
public function rules()
{
$rules = [];
$request = $this->request;
if ($request->has('transfer_per_day')) {
if (!empty($request->transfer_per_day)) {
$rules['transfer_per_day'] = "numeric";
}
}
if ($request->has('call_per_day')) {
if (!empty($request->call_per_day)) {
$rules['call_per_day'] = "numeric";
}
}
if ($request->has('rea_sign_up')) {
if (!empty($request->rea_sign_up)) {
$rules['rea_sign_up'] = "numeric";
}
}
if ($request->has('tbd_assigned')) {
if (!empty($request->tbd_assigned)) {
$rules['tbd_assigned'] = "numeric";
}
}
if ($request->has('no_of_matches')) {
if (!empty($request->no_of_matches)) {
$rules['no_of_matches'] = "numeric";
}
}
if ($request->has('leads')) {
if (!empty($request->leads)) {
$rules['leads'] = "numeric";
}
}
if ($request->has('conversations')) {
if (!empty($request->conversations)) {
$rules['conversations'] = "numeric";
}
}
return $rules;
}
Although I check the type in which request is being sent from controller and recieved from the request validation and it is Object. So how can I solve the issue.

Custom directive to check the value of two or more fields

I tried my best to write a custom directive in Apollo Server Express to validate two input type fields.
But the code even works but the recording of the mutation already occurs.
I appreciate if anyone can help me fix any error in the code below.
This is just sample code, I need to test the value in two fields at the same time.
const { SchemaDirectiveVisitor } = require('apollo-server');
const { GraphQLScalarType, GraphQLNonNull, defaultFieldResolver } = require('graphql');
class RegexDirective extends SchemaDirectiveVisitor {
visitInputFieldDefinition(field) {
this.wrapType(field);
}
visitFieldDefinition(field) {
this.wrapType(field);
}
wrapType(field) {
const { resolve = defaultFieldResolver } = field;
field.resolve = async function (source, args, context, info) {
if (info.operation.operation === 'mutation') {
if (source[field.name] === 'error') {
throw new Error(`Find error: ${field.name}`);
}
}
return await resolve.call(this, source, args, context, info);
};
if (
field.type instanceof GraphQLNonNull
&& field.type.ofType instanceof GraphQLScalarType
) {
field.type = new GraphQLNonNull(
new RegexType(field.type.ofType),
);
} else if (field.type instanceof GraphQLScalarType) {
field.type = new RegexType(field.type);
} else {
// throw new Error(`Not a scalar type: ${field.type}`);
}
}
}
class RegexType extends GraphQLScalarType {
constructor(type) {
super({
name: 'RegexScalar',
serialize(value) {
return type.serialize(value);
},
parseValue(value) {
return type.parseValue(value);
},
parseLiteral(ast) {
const result = type.parseLiteral(ast);
return result;
},
});
}
}
module.exports = RegexDirective;

Flutter FutureBuilder returning null data

I'm new to Flutter and Dart, and I'm trying to write a application to test it.
I have an api that I'm getting the data for the app, and was trying to use the StatefulWidget and the FutureBuilder.
When I run the method to call the api I have the results (used print() to test it), but when I get the data from loadData method it retrives null.
So loadData prints the data, initState and FutureBuilder the data returns null. What am I missing here.
I have added the service and the models used for the request... hope it help.
Future<CoachesModelRes> loadData(Profile _profile) async {
await getPost(_profile.getToken()).then((response) {
if (response.statusCode == 200) {
CoachesModelRes coaches = coachesModel.postFromJson(response.body);
if (coaches.count > 0) {
print(coaches.count);
print(coaches.coaches[0].description);
return coaches;
} else {
return null;
}
} else {
String code = response.statusCode.toString();
return null;
}
}).catchError((error) {
print(error.toString());
return null;
});
}
#override
void initState() {
super.initState();
print(widget.profile.getToken());
data = loadData(widget.profile);
data.then((data_) async {
var cenas = data_.count;
print("asdasd $cenas");
});
}
Future<CoachesModelRes> data;
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: appWhiteColor,
appBar: applicationBar(),
drawer: adminDrawer(widget.profile, AdminDrawerListEnum.coaches, context),
body: FutureBuilder<CoachesModelRes>(
future: data,
builder: (context, snapshot) {
//print(snapshot.data.count.toString());
if (snapshot.hasData) {
return Text("nop");
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
return Text("nop");
// By default, show a loading spinner.
return CircularProgressIndicator();
},
),
);
}
Future<http.Response> getPost(String token) async {
final response = await http.get(new Uri.http("$apiUrl", "$coachesEndPoint"),
headers: {
HttpHeaders.contentTypeHeader: 'application/json',
HttpHeaders.authorizationHeader : 'Bearer $token'
},
);
return response;
}
CoachesModelRes postFromJson(String str) => CoachesModelRes.fromJson(json.decode(str));
class CoachesModelRes {
int count;
List<CoachModelRes> coaches;
CoachesModelRes({
this.count,
this.coaches,
});
factory CoachesModelRes.fromJson(Map<String, dynamic> json) => new CoachesModelRes(
count: json["count"],
coaches: (json["coaches"] as List).map((i) => CoachModelRes.fromJson(i)).toList(),
);
}
CoachModelRes postFromJson(String str) => CoachModelRes.fromJson(json.decode(str));
class CoachModelRes {
String id;
String firstName;
String lastName;
String description;
String username;
String notes;
List<String> roles;
CoachModelRes({
this.id,
this.firstName,
this.lastName,
this.description,
this.username,
this.notes,
this.roles,
});
factory CoachModelRes.fromJson(Map<String, dynamic> json) => new CoachModelRes(
id: json["id"],
firstName: json["firstName"],
lastName: json["lastName"],
description: json["description"],
username: json["username"],
notes: json["notes"],
roles: new List<String>.from(json["roles"]),
);
}
Future<CoachesModelRes> loadData(Profile _profile) async {
final response = await getPost(_profile.getToken());
try{if (response.statusCode == 200) {
CoachesModelRes coaches = coachesModel.postFromJson(response.body);
if (coaches.count > 0) {
print(coaches.count);
print(coaches.coaches[0].description);
return coaches;
} else {
return null;
}
} else {
String code = response.statusCode.toString();
return null;
}}catch(e){
return null ;
}
}
#override
void initState() {
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: appWhiteColor,
appBar: applicationBar(),
drawer: adminDrawer(widget.profile, AdminDrawerListEnum.coaches, context),
body: FutureBuilder<CoachesModelRes>(
future: loadData(widget.profile),
builder: (context, snapshot) {
//print(snapshot.data.count.toString());
if (snapshot.hasData) {
return Text("nop");
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
return Text("nop");
// By default, show a loading spinner.
return CircularProgressIndicator();
},
),
);
}
The issue here is that the return statement should be at the end of the method.
Because the getPost will return data to the loadData.
And when the getPost finishes the loadData will return data to the method that invoked him.
In my case, the loadData is not returning anything so the snapshot in the FutureBuilder it's always null.
It's logic that it is this way now, but at the time I could not figure it out :\
Future<CoachesModelRes> loadData(Profile _profile) async {
// So I need to create a variable to return
CoachesModelRes response;
//-----
await getPost(_profile.getToken()).then((response) {
if (response.statusCode == 200) {
CoachesModelRes coaches = coachesModel.postFromJson(response.body);
if (coaches.count > 0) {
print(coaches.count);
print(coaches.coaches[0].description);
// Set the variable value
response = coaches;
//-----
} else {
// Set the variable value
response = null;
//-----
}
} else {
String code = response.statusCode.toString();
// Set the variable value
response = null;
//-----
}
}).catchError((error) {
print(error.toString());
// Set the variable value
response = null;
//-----
});
// And at the end return the response variable
return response;
//-----
}

Dynamically addTrack to offerer from answerer onnegotiationneeded in webrtc

Is there anyway to notify offerer that non-existing track before just added to get the new stream from the answerer from the code below?
For my current issue now here is that the offerer can add new non-existing track and onnegotiationneeded will be fired and will also be able to createOffer and update media successfully, but when answerer do same process onnegotiationneeded fired normally also from the answerer but no media will be exchanged just because offerer do not have any new track on his end!
I use replaceOrAddTrack(remotePartiID, track, TrackKind) in adding and replacing of tracks
Only the replace works with either ends if it has same track kind from initial connection
_cfg = {
sdpConstraints: {
mandatory: {
OfferToReceiveAudio: true,
OfferToReceiveVideo: true,
VoiceActivityDetection: true,
IceRestart: true
},
optional: []
}
...
};
var channels_wrap = (function() {
return {
...
init: function() {
_cfg.defaultChannel.on('message', (message) => {
if (_cfg.enableLog) {
console.log('Client received message:', message);
}
if (message.type === 'newparticipant') {
var partID = message.from;
var partData = message.fromData;
// Open a new communication channel to the new participant
_cfg.offerChannels[partID] = this.openSignalingChannel(partID);
// Wait for answers (to offers) from the new participant
_cfg.offerChannels[partID].on('message', (msg) => {
if (msg.dest === _cfg.myID) {
if (msg.type === 'reoffer') {
if (_cfg.opc.hasOwnProperty(msg.from)) {
console.log('reoffering')
_cfg.opc[msg.from].negotiationNeeded();
}
} else
if (msg.type === 'answer') {
_cfg.opc[msg.from].peer.setRemoteDescription(new RTCSessionDescription(msg.snDescription),
handlers_wrap.setRemoteDescriptionSuccess,
handlers_wrap.setRemoteDescriptionError);
} else if (msg.type === 'candidate') {
var candidate = new RTCIceCandidate({
sdpMLineIndex: msg.label,
candidate: msg.candidate
});
if (_cfg.enableLog) {
console.log('got ice candidate from ' + msg.from);
}
_cfg.opc[msg.from].peer.addIceCandidate(candidate, handlers_wrap.addIceCandidateSuccess, handlers_wrap.addIceCandidateError);
}
}
});
// Send an offer to the new participant
dialogs_wrap.createOffer(partID, partData);
} else if (message.type === 'bye') {
handlers_wrap.hangup(message.from, message.fromData);
}
});
},
initPrivateChannel: function() {
// Open a private channel (namespace = _cfg.myID) to receive offers
_cfg.privateAnswerChannel = this.openSignalingChannel(_cfg.myID);
// Wait for offers or ice candidates
_cfg.privateAnswerChannel.on('message', (message) => {
if (message.dest === _cfg.myID) {
if (message.type === 'offer') {
var to = message.from;
dialogs_wrap.createAnswer(message.snDescription, _cfg.privateAnswerChannel, to, message.fromData);
} else if (message.type === 'candidate') {
var candidate = new RTCIceCandidate({
sdpMLineIndex: message.label,
candidate: message.candidate
});
_cfg.apc[message.from].peer.addIceCandidate(candidate, handlers_wrap.addIceCandidateSuccess, handlers_wrap.addIceCandidateError);
}
}
});
}
};
})();
var tracks_wrap = (function() {
return {
getParticipants: function(partID = null) {
var participants = {};
if (partID) {
if (_cfg.opc.hasOwnProperty(partID)) {
participants[partID] = {
ID: partID,
type: 'opc'
};
} else
if (_cfg.apc.hasOwnProperty(partID)) {
participants[partID] = {
ID: partID,
type: 'apc'
};
}
} else {
for (let key in _cfg.opc) {
participants[key] = {
ID: key,
type: 'opc'
};
}
for (let key in _cfg.apc) {
participants[key] = {
ID: key,
type: 'apc'
};
}
}
return participants;
},
replaceOrAddTrack: function(remotePartiID, track, TrackKind) {
if (!TrackKind) {
return;
}
var participants = this.getParticipants(remotePartiID);
for (var partiID in participants) {
var peer = null;
if (participants[partiID].type === 'apc' && _cfg.apc.hasOwnProperty(partiID)) {
peer = _cfg.apc[partiID].peer;
} else if (participants[partiID].type === 'opc' && _cfg.opc.hasOwnProperty(partiID)) {
peer = _cfg.opc[partiID].peer;
} else {
continue;
}
var foundTrack = null;
peer.getSenders().forEach(function(rtpSender) {
if (rtpSender.track && TrackKind === rtpSender.track.kind) {
foundTrack = true;
rtpSender.replaceTrack(track);
}
});
if (!foundTrack) {
peer.addTrack(track, _cfg.localStream); //This work only if it is offerrer that add track but not working with answerer even if i tell the offerer to send offer again
}
}
}
};
})();
var dialogs_wrap = (function() {
return {
/**
*
* Send an offer to peer with id partID and metadata as partData
*
*/
createOffer: function(partID, partData) {
if (_cfg.enableLog) {
console.log('Creating offer for peer ' + partID, partData);
}
var opcPeer = new RTCPeerConnection(_cfg.pcConfig, _cfg.peerSetup);
_cfg.opc[partID] = {};
_cfg.opc[partID].peer = opcPeer;
_cfg.opc[partID].peer.onicecandidate = handlers_wrap.handleIceCandidateAnswer(_cfg.offerChannels[partID], partID, partData);
_cfg.opc[partID].peer.ontrack = handlers_wrap.handleRemoteStreamAdded(partID, partData);
_cfg.opc[partID].peer.onremovetrack = handlers_wrap.handleRemoteStreamRemoved(partID, partData);
_cfg.localStream.getTracks().forEach(track => _cfg.opc[partID].peer.addTrack(track, _cfg.localStream));
try {
_cfg.sendChannel[partID] = _cfg.opc[partID].peer.createDataChannel("sendDataChannel", {
reliable: false
});
_cfg.sendChannel[partID].onmessage = handlers_wrap.handleMessage;
if (_cfg.enableLog) {
console.log('Created send data channel');
}
} catch (e) {
alert('Failed to create data channel. \n You need supported RtpDataChannel enabled browser');
console.log('createDataChannel() failed with exception: ', e.message);
}
_cfg.sendChannel[partID].onopen = handlers_wrap.handleSendChannelStateChange(partID);
_cfg.sendChannel[partID].onclose = handlers_wrap.handleSendChannelStateChange(partID);
var onSuccess = (partID, partData) => {
var channel = _cfg.offerChannels[partID];
if (_cfg.enableLog) {
console.log('Sending offering');
}
channel.emit('message', {
snDescription: _cfg.opc[partID].peer.localDescription,
from: _cfg.myID,
fromData: _cfg.myData,
type: 'offer',
dest: partID,
destData: partData
});
}
_cfg.opc[partID].negotiationNeeded = () => {
_cfg.opc[partID].peer.createOffer(_cfg.sdpConstraints).then(offer => {
offer.sdp = sdp_wrap.SDPController(offer.sdp);
return _cfg.opc[partID].peer.setLocalDescription(offer)
})
.then(() => onSuccess(partID, partData)).catch(handlers_wrap.handleCreateOfferError);
}
_cfg.opc[partID].peer.onnegotiationneeded = () => {
_cfg.opc[partID].negotiationNeeded();
}
},
createAnswer: function(snDescription, cnl, to, toData) {
if (_cfg.enableLog) {
console.log('Creating answer for peer ' + to);
}
if (!_cfg.apc.hasOwnProperty(to)) {
var apcPeer = new RTCPeerConnection(_cfg.pcConfig, _cfg.peerSetup);
//apcPeer.setConfiguration(_cfg.pcConfig);
_cfg.apc[to] = {};
_cfg.apc[to].peer = apcPeer;
_cfg.apc[to].peer.onicecandidate = handlers_wrap.handleIceCandidateAnswer(cnl, to, toData);
_cfg.apc[to].peer.ontrack = handlers_wrap.handleRemoteStreamAdded(to, toData);
_cfg.apc[to].peer.onremovetrack = handlers_wrap.handleRemoteStreamRemoved(to, toData);
_cfg.localStream.getTracks().forEach(track => _cfg.apc[to].peer.addTrack(track, _cfg.localStream));
_cfg.apc[to].peer.ondatachannel = handlers_wrap.gotReceiveChannel(to);
}
_cfg.apc[to].peer.setRemoteDescription(new RTCSessionDescription(snDescription), handlers_wrap.setRemoteDescriptionSuccess, handlers_wrap.setRemoteDescriptionError);
var onSuccess = (channel) => {
if (_cfg.enableLog) {
console.log('Sending answering');
}
channel.emit('message', {
snDescription: _cfg.apc[to].peer.localDescription,
from: _cfg.myID,
fromData: _cfg.myData,
type: 'answer',
dest: to,
destData: toData
});
}
_cfg.apc[to].peer.createAnswer().then(function(answer) {
answer.sdp = sdp_wrap.SDPController(answer.sdp);
return _cfg.apc[to].peer.setLocalDescription(answer);
})
.then(() => onSuccess(cnl))
.catch(handlers_wrap.handleCreateAnswerError);
var negotiationNeeded = false;
_cfg.apc[to].peer.onnegotiationneeded = (ev) => {
if (!negotiationNeeded) {
negotiationNeeded = true;
return;
}
//So i tried to create this to tell the offerer to do offer again, offerer do resend offer but nothing seem to happen
cnl.emit('message', {
from: _cfg.myID,
fromData: _cfg.myData,
type: 'reoffer',
dest: to,
destData: toData
});
}
}
};
})();

React Native SectionList (title, data) - Search in the data field

I am trying to build Search function in SectionList. I have search inside the 'data' (second field) and not inside 'title' but I am not able to make it work.
My Data is about the Flat / resident details of an Apartment -
sectiondata =
[{"title":"GROUND FLOOR",
"data":[
{"id":"48","res_type":"owner","user_name":"Ashwani","flat_id":"1","flat_name":"001","floor_no":"GROUND FLOOR","floor_int":"0","signal_player_id":"aa","user_phone":"98855550"},
{"id":"49","res_type":"owner","user_name":"Rahul","flat_id":"2","flat_name":"002","floor_no":"GROUND FLOOR","floor_int":"0","signal_player_id":"aa","user_phone":"999999"}
]
}]
I am trying something like this but it is not working.
searchFilterFunction = (text) => {
let search = text.toLowerCase();
this.setState({
check: this.state.sectiondata.filter(
obj => obj.data['flat_name'].toLowerCase().includes(search))
});
}
How to filter data base on name? Please assist here.
Thanks.
You can try to search like this:
onChangeText(text) {
if (text.trim().length > 0) {
var temp = []
sectiondata.map((item) => {
var dataItem = {};
var brandData = [];
item.data.map((searchItem) => {
let flatName = searchItem.flat_name
if (flatName.match(text)) {
brandData.push(searchItem);
}
})
if (brandData.length > 0) {
} else {
return null;
}
dataItem.brandData = brandData;
temp.push(dataItem);
this.setState({
sectiondata: temp
})
})
} else {
this.setState({
sectiondata: this.state.tempData
})
}
}
searchFilterFunction(text) {
if( text == undefined || text == '') {
this.setState({
sectiondata: this.arrayholder
})
return;
}
if (text.trim().length > 0) {
var temp = []
this.state.sectiondata.map((item) => {
var dataItem = {};
var title = item.title;
var brandData = [];
item.data.map((searchItem) => {
let flatName = searchItem.flat_name
if (flatName.match(text)) {
brandData.push(searchItem);
}
})
if (brandData.length > 0) {
} else {
return null;
}
dataItem.title = title;
dataItem.data = brandData;
temp.push(dataItem);
this.setState({
sectiondata: temp
})
})