How to intentionally make all Mirage JS request return 500? - http-status-code-500

Trying to make MULTIPLE mocked service response 500 for testing any suggestions?

Miragejs has a Response class which you can instantiate and return from your response handlers. The first argument in the constructor is the status:
import { Response } from 'miragejs';
this.get('/users', () => {
return new Response(500, { some: 'header' }, { errors: [ 'name cannot be blank'] });
});

Related

How to use observable data from an external api in nestjs?

Im trying to use from a external api in nestjs with axios.
#Injectable()
export class PIntegration {
constructor(private httpService: HttpService) { }
API = process.env.API || 'http://localhost:3000';
header = { headers: { 'Content-Type': 'application/json' } };
async getPrestacionById(id: string): Promise<Observable<IPrestacion>>{
return this.httpService.get(`${this.API}/prestacion/${id}`, this.header).pipe(map((res) => res.data));
}
}
And my service class looks like this:
#Injectable()
export class ProductService{
constructor(private pIntegration: PIntegration){}
async producto(id: string) {
const infoPrestacion = await this.pIntegration.getPrestacionById(id);
console.log({ infoPrestacion })
if (infoPrestacion)
{
if (infoPrestacion.detalles) {
console.log(infoPrestacion.detalles)
console.log("tiene detalles")
}
}
return infoPrestacion;
}
}
However if i console.log the value "infoPrestacion" this is the result:
{
infoPrestacion: Observable {
source: Observable { _subscribe: [Function (anonymous)] },
operator: [Function (anonymous)]
}
}
and it doesnt get to the second since it's not resolved yet. Is it possible to wait for the result until it's resolved (i don't have any config for the HttpModule) ? The return actually gets the object itself "infoPrestacion" but i need to work with the values and not return that object.
I solved my problem with this, i hope this might fit your needs.
If you take your observable as a promise there are two solution that might fit for you.
In the class you are using an external api:
Add lastValueFrom which converts an observable to a promise by subscribing to the observable, waiting for it to complete, and resolving the returned promise with the last value from the observed stream.
firstValueFrom could be also a solution, does the opposite of lastValuefrom getting the first element as your promise is solved.
#Injectable()
export class PIntegration {
constructor(private httpService: HttpService) { }
API = process.env.API || 'http://localhost:3000';
header = { headers: { 'Content-Type': 'application/json' } };
async getPrestacionById(id: string): Promise<IPrestacion>{
return lastValueFrom(this.httpService.get(`${this.API}/prestacion/${id}`, this.header).pipe(map((res) => res.data)));
}
}

Angular 12 how to convert date object to string using http interceptor

I am trying to convert the date property to string object for all http request. Currently converting individual request body as below;
modifiedOn: modifiedOn?.map(x => moment(x).format('YYYY-MM-DD HH:mm:ss')),
But I would like this to apply for all http request in the interceptor. Can anyone help how to do this. my interceptor is as below:
#Injectable()
export class VerifyAuthorisationInterceptor implements HttpInterceptor {
constructor(#Inject(ENVIRONMENT) private environment: IEnvironment) {}
intercept(
request: HttpRequest<unknown>,
next: HttpHandler
): Observable<HttpEvent<unknown>> {
return next.handle(request).pipe(
map((event: HttpEvent<unknown>) => {
return event;
}),
catchError((error: HttpErrorResponse) => {
if (error.status === 401 && error.statusText === 'Unauthorized') {
const returnUrl = window.location.href;
window.location.href = radarWebUrl;
}
return throwError(error);
})
);
}
}
Add this to your intercept method before return. It will check if your request contains body and any Date elements and then converts those:
if(request?.body) {
Object.keys(request.body).forEach((key: any) => {
if(request.body[key] instanceof Date) {
request.body[key] = moment(request.body[key]).format('YYYY-MM-DD HH:mm:ss');
}
});
}

Wuxt.js (Nuxt.js) getting out data from axios response

I want to fetch out menu items from the Wordpress json response with Wuxt framework (Nuxt + Wordpress), but I can't access the data object outside the fetch (error message is that data is not defined)
This is my code
<script>
import axios from 'axios'
import Logo from '~/components/Logo'
export default {
components: {
Logo
},
async fetch ({ params, error }) {
try {
let { data } = await axios.get('http://localhost:3080/wp-json/wuxt/v1/menu')
return data
} catch (e) {
error({ message: 'Not found', statusCode: 404 })
}
}
}
</script>
How can the data object be accessed, for inserting into the template?
If you are using fetch than all your data should be commiting into store, and accessed from it. If you want to return data, use asyncData method.
I had to change the code a bit, that it returns a data function with variable, so it looks like this.
export default {
components: {
Logo
},
data() {
return { menus: [] }
},
mounted() {
fetch('http://localhost:3080/wp-json/wuxt/v1/menu')
.then(response => {
response.json().then(menus => {
this.menus = menus;
})
})
}
}

api request returns undefined

maybe is a stupid question but,
when I'm calling api from 'outside' function it always returns undefined,
for example:
actions.js
import axios from 'axios'
export function getProducts() {
axios.get('http://localhost:8000/api/products').then((response) => {
return response;
});
}
and then in a component:
mounted() {
this.products = getProducts();
console.log(this.products);
}
returns undefined
of course when I make a request from component it returns result
mounted() {
axios.get('http://localhost:8000/api/products').then((response) => {
this.products = response;
console.log(this.products);
});
}
Why is this happening and how can I solve this problem?
Thanks
You are returning the response value in the then callback of the axios.get call. However, your getProducts function doesn't return anything.
Simply return the axios.get call:
export function getProducts() {
return axios.get('http://localhost:8000/api/products');
}
Then, the result of getProducts will be the Promise returned by axios.get(). So, you can add a then callback on the result of getProducts and set you this.products that way:
mounted() {
getProducts().then(products => this.products = products);
}

cannot retrieve data from angular http

I'm trying to retrieve data from a collection in my mongodb using http module using the code below,
getPosts() {
return this.http.get('http://localhost:5005/blog/getposts').map(res => {
console.log("mapped result",res);
res.json()
});
}
It fails everytime with a response
Unexpected token < in JSON at position 0
at JSON.parse (<anonymous>)
at Response.webpackJsonp.../../../http/#angular/http.es5.js.Body.json (http.es5.js:797)
at MapSubscriber.project (auth.service.ts:45)
at MapSubscriber.webpackJsonp.../../../../rxjs/operators/map.js.MapSubscriber._next (map.js:79)
at MapSubscriber.webpackJsonp.../../../../rxjs/Subscriber.js.Subscriber.next (Subscriber.js:89)
at XMLHttpRequest.onLoad (http.es5.js:1226)
at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:425)
at Object.onInvokeTask (core.es5.js:3881)
at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:424)
at Zone.webpackJsonp.../../../../zone.js/dist/zone.js.Zone.runTask (zone.js:192)
but when I try it with postman, I'm getting the expected result which is this,
I'm returning the response from the service and subscribing its data from a component like this,
ngOnInit() {
this.auth.getPosts().subscribe(data => {
this.value = data.posts;
console.log("blog component",this.value)
},err => {
console.log(err);
})
}
What am I doing wrong? Any help would be much appreciated
You need to convert the response in map and subscribe to it to get the final JSON response
Updated code would look like this-
getPosts() {
return this.http.get('http://localhost:5005/blog/getposts')
.map(res => res.json())
.subscribe((data: any) => {
//console.log(data);
});
}
I hope this helps. :)
Try returning inside the .map()
getPosts() {
return this.http.get('http://localhost:5005/blog/getposts').map(res => {
console.log("mapped result",res);
return res.json()
});
}
}
or drop the brackets (this gives you an implied return),
getPosts() {
return this.http.get('http://localhost:5005/blog/getposts')
.map(res => res.json() );
}
}