How to add scalar type for Graphql date with time in Apollo server? - sql-server

I have a Datetime column in my SQL Server database which looks like this: 2022-09-23 03:21:22.000
I am trying to add this datatype in my typedefs for Nodejs (Javascript) by defining a custom scalar by referring to this document: https://www.apollographql.com/docs/apollo-server/schema/custom-scalars/
I am stuck and not understanding how to proceed. I have defined the scalar type in my schema.graphql file. Where should I add the logic for this schema? It says to add in resolvers file, my resolvers file looks like this:
const { model1, model2, sequelize } = require('../models');
const initModels = require("../models/init-models");
const GraphQLScalarType = require("graphql")
const models = initModels(sequelize);
const Query = {
model1: async () => {
try {
const Battery = await model1.findAll();
return Battery;
} catch(err){
console.log(err)
}
},
model2: async () => {
try {
const cell = await model2.findAll();
return cell;
} catch(err) {
console.log(err)
}
}
}
module.exports = {Query}
The resolver file runs without any error and I am able to get data in my server. How do I add the DateTime schema logic here?

Related

How to use API Route in next js?

I am learning how to design API and at the same time how to use next.js API route.
I have set my first route api/property/[propertyId] that returns the specific property detail.
Now I am trying to set a dynamic route for the specific property id in the page folder page/property/[propertyId]. My issue is when I am getting directed on the specific page the data is not there as expected. I am receiving a response for error message.
Can someone point out what I did wrong, please?
pages>api>property>[propertyId]
export default function propertyHandler ({query : {propertyId} } ,res) {
var parser = new xml2js.Parser({explicitArray : false});
const data = fs.readFileSync(path.join(process.cwd(),'listing.xml'))
parser.parseString(data,function (err, results){
results = results.client.secondhandListing.property
const filteredProp = results.filter((property) => property.id === propertyId)
filteredProp.length > 0 ? res.status(200).json(filteredProp[0]) : res.status(404).json({message: `Property with id: ${propertyId} not found.` })
})
}
pages>property>[id].js
export const getDetails = async() => {
const res = await fetch(`${baseUrl}/api/property/[property.Id]}`)
const data = res.json()
return data
}
export async function getServerSideProps({params: { id } }) {
const data = await getDetails(`${baseUrl}/api/property/${id}`)
return {
props: {
propertyDetails: data
}
}
}
I got the answer to my mistake from somewhere else. It was my getdetails function that was wrong.
I have amended it to:
export const getDetails = async(baseUrl)=>{
const res = await fetch(baseUrl)
const data = await res.json()
return data
};
and it worked.

CastError: Cast to ObjectId failed for value "undefined" (type string) at path "_id" for model

I am developing an app but when i try to publish a course the error i am getting is kind of wired but might be related to the mongoose mondo db database.
export const publishCourse = async (req, res) => {
try {
const { courseId } = req.params;
// find post
const course = await Course.findById(courseId)
.select("instructor")
.exec();
// is owner?
if (course.instructor._id != req.user._id) {
return res.status(400).send("Unauthorized");
}
const updated = await Course.findByIdAndUpdate(courseId, {published: true}, {new: true}).exec();
res.json(updated);
} catch (err) {
console.log(err);
return res.status(400).send("Publish course failed");
}
};
maybe the parameter you retrieve from the request params const { courseId } = req.params is not a valid objectId hence findById throws the error you mentioned, try to make sure the courseId is a valid objectId before calling findById, maybe you can use this in your code:
const { courseId } = req.params;
if(ObjectId.isValid(courseId)){
// throw some error document not found for example.
}

Discrepancy in data on recieving at frontend

I am fetching data from backend which works fine but on receiving it on frontend the _id property is turned to null.
Here is the backend code .The _id is correct currently as can be seen in console(terminal)
export const getPosts=async(req,res)=>{
try {
const postMessages=await PostMessage.find()
console.log(postMessages[0]._id);
res.status(200).json(postMessages)
} catch (error) {
res.status(404).json({message:error.message})
}
}
But on frontend the property shows null .The weird thing is on separately console logging the property of an individual item it shows correct value. Here is the screenshot.
const [state, dispatch] = useReducer(reducer, initialState)
const getPosts=()=>{
(async () => {
dispatch({type:'LOADING'})
try {
const res = await fetch("http://localhost:5000/posts")
const data = await res.json()
console.log(data,data[0]._id);
dispatch({type:'FETCH_ALL_POSTS',payload:data})
} catch (error) {
dispatch({type:'FETCH_ERROR',payload:error})
}
})()
dispatch({type:'FETCH_ALL_POSTS'})
}

React SignalR callback missing constants

I am using React with react hooks and SignalR. I have some consts properties that are linked to input fields
const [name, setEmployeeName] = useState<string>('');
const [id, setEmployeeId] = useState<string>('');
const [project, setProjectName] = useState<string>('');
And following a chat tutorial setup the connection and subscriptions in useEffect like
useEffect(() => {
// Set the initial SignalR Hub Connection.
const createHubConnection = async () => {
const hubConnect = new HubConnectionBuilder()
.withUrl(`${url}/emp`)
.build()
try {
await hubConnect.start()
console.log('Connection successful!')
hubConnect.on('update', (employee: Employee) => {
if(id === employee.id) {
setEmployeeName(employee.name)
setProjectName(employee.project)
}
})
}
catch (err) {
alert(err);
console.log(err);
console.log('Error while establishing connection: ' + { err })
}
setHubConnection(hubConnect);
}
createHubConnection();
}, [])
So when I invoke the 'update' method from the server side and enter the implementation here, all those consts are missing and are ''.
So this if(id === employee.id) is always false.
For me it seems like I need to bind .this but I don't think we have this in React.
Ok so after further thinking I realised this was not a good approach. So i tweaked the subscription. Linked the input change to this method:
function onIdChange(_id: string) {
if(_id !== id) {
hubConnection!.off(`updateEmployee/${id}`)
setEmployeeId(_id)
hubConnection!.on(`updateEmployee/${_id}`, (employee: Employee) => {
setEmployeeName(employee.name)
setProjectName(employee.project)
})
}
}
So now from the server, whenever I want to invoke a method with the employeerId, I have already set a subscription and once I call it I no longer need to do the if statement.

RelayObservable: Unhandled Error TypeError: Cannot read property 'subscribe' of undefined in React and Relay

I have followed the subscription tutorial on How to GraphQL React + Relay (https://relay.dev/docs/en/subscriptions) but still not working.
I'm using Relay Modern in my app and have successfully integrated query but not working the requestSubscription function.
Any help would be awesome.
My environment.js file:
function setupSubscription(
config,
variables,
cacheConfig,
observer,
) {
const query = config.text
const subscriptionClient = new SubscriptionClient('ws://192.168.1.19:8000/subscriptions', {reconnect: true});
const id = subscriptionClient.on({query, variables}, (error, result) => {
console.log(result,'result');
observer.onNext({data: result})
})
}
const network = Network.create(fetchQuery, setupSubscription)
const environment = new Environment({
network,
store
});
export default environment;
- My Subscription.js file:
const subscription = graphql`
subscription newVoteSubscription {
leaderboardUpdate {
id,
game_id,
event_id,
colarr,
rowarr
}
}
`;
function newVoteSubscription(callback) {
const variables = {};
return requestSubscription(environment, {
subscription: subscription,
variables: variables,
onError: (error)=> {
console.log(error, "error");
},
onNext: (res) => {
console.log(res,'onNext');
// callback();
},
updater: proxyStore => {
console.log(proxyStore,'proxyStore');
},
onCompleted: () => {
console.log('test');
},
});
}
export default newVoteSubscription;
I had trouble with the network as well. On Relay 7 using an Observable worked for me. This also handles error cases and the server closing the subscription.
const subscriptionClient = new SubscriptionClient('ws://192.168.1.19:8000/subscriptions', {reconnect: true})
function setupSubscription(
request,
variables,
cacheConfig,
) {
const query = request.text;
// Observable is imported from the relay-runtime package
return Observable.create(sink => {
const c = subscriptionClient.request({ query, variables }).subscribe(sink);
return c.unsubscribe;
});
}
I'm not sure why i've gone with the sink / unsubscribe approach, but this is what worked for me. As far as i remember the observable types used by relay and subscriptions-transport-ws were not compatible.
Also i'd advise you to hoist the new SubscriptionClient() call outside of the setupSubscription function as otherwise you'll open a new WebSocket for each subscription request.
I got the response, but now observer.onNext is undefined.
My updated code environment.js:
const setupSubscription = (config, variables, cacheConfig, observer) => {
const query = config.text
const subscriptionClient = new SubscriptionClient('ws://192.168.1.19:8000/subscriptions', {reconnect: true})
subscriptionClient.request({ query, variables }).subscribe((result) => {
observer.onNext({data: result})
});
return Observable.create(() => {
return subscriptionClient;
});
}
const environment = new Environment({
network: Network.create(fetchQuery, setupSubscription),
store: new Store(new RecordSource())
});

Resources