this example is from a tutorial and I get an error
Exception: Server error; cause: Expected a value of type 'int', but got one of type 'String'
terminal pycharm backend gives data code 200
[09/Feb/2020 11:45:48] "GET /adverts/ HTTP/1.1" 200 492
class Hero {
final int id;
String name;
Hero(this.id, this.name);
factory Hero.fromJson(Map<String, dynamic> hero) =>
Hero(_toInt(hero['id']), hero['name']);
Map toJson() => {'id': id, 'name': name};
}
int _toInt(id) => id is int ? id : int.parse(id);
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart';
import 'hero.dart';
class HeroService {
static final _headers = {'Content-Type': 'application/json'};
static const _heroesUrl = 'http://127.0.0.1:8000/heroes'; // URL to
web API
final Client _http;
HeroService(this._http);
Future<List<Hero>> getAll() async {
try {
final response = await _http.get(_heroesUrl);
final heroes = (_extractData(response) as List)
.map((value) => Hero.fromJson(value))
.toList();
return heroes;
} catch (e) {
throw _handleError(e);
}
}
Future<Hero> create(String name) async {
try {
final response = await _http.post(_heroesUrl,
headers: _headers, body: json.encode({'name': name}));
return Hero.fromJson(_extractData(response));
} catch (e) {
throw _handleError(e);
}
}
dynamic _extractData(Response resp) => json.decode(resp.body)['data'];
Exception _handleError(dynamic e) {
print(e); // for demo purposes only
return Exception('Server error; cause: $e');
}
}
I don't have json this -> data: and to get the data you need from the string -> dynamic _extractData (Response resp) => json.decode (resp.body) ['data']; delete ['data'] or edit JSON generation django_rest, if you have information on how to get a JSON like {'data':[ ]} in drf, I'm happy to read it
Related
I have two databases that I need to interact with in my code. I have a simple function that takes an object and writes it to my PostgreSQL database using Prisma. I've tested the function with Postman, and it works perfectly, but when I try to execute it using a Jest mock (using the singleton pattern found in the Prisma unit testing guide), it returns undefined indicating that it didn't interact with the database and create the new record. Here's my code:
/prisma/clinical-schema.prisma
generator client {
provider = "prisma-client-js"
output = "./generated/clinical"
}
datasource clinicalDatabase {
provider = "postgresql"
url = "postgresql://postgres:postgres#localhost:5432/clinical-data?schema=public"
}
model pcc_webhook_update {
id Int #id #default(autoincrement())
event_type String
organization_id Int
facility_id Int
patient_id Int
resource_id String?
webhook_date DateTime #default(now()) #clinicalDatabase.Timestamptz(6)
status pcc_webhook_update_status #default(pending)
status_changed_date DateTime? #clinicalDatabase.Timestamptz(6)
error_count Int #default(0)
##unique([organization_id, facility_id, patient_id, resource_id, event_type, status])
}
enum pcc_webhook_update_status {
pending
processing
processed
error
}
/prisma/clinical-client.ts
import { PrismaClient } from './generated/clinical';
const prismaClinical = new PrismaClient();
export default prismaClinical;
/testing/prisma-clinical-mock.ts
import { PrismaClient } from '../prisma/generated/clinical';
import { mockDeep, mockReset, DeepMockProxy } from 'jest-mock-extended';
import prisma from '../prisma/clinical-client';
jest.mock('../prisma/clinical-client', () => ({
__esModule: true,
default: mockDeep<PrismaClient>()
}));
beforeEach(() => {
mockReset(prismaClinicalMock);
});
export const prismaClinicalMock = prisma as unknown as DeepMockProxy<PrismaClient>;
Everything up to this point follows the conventions outlined by the Prisma unit testing docs. The only modification I made was to make it database specific. Below is my function and tests. The request object in handle-pcc-webhooks.ts is a sample http request object, the body of which contains the webhook data I care about.
/functions/handle-pcc-webhooks/handler.ts
import prismaClinical from '../../../prisma/clinical-client';
import { pcc_webhook_update } from '../../../prisma/generated/clinical';
import { requestObject } from './handler.types';
export const handlePccWebhook = async (request: requestObject) => {
try {
const webhook = JSON.parse(request.body);
// if the webhook doesn't include a resource id array, set it to an array with an empty string to ensure processing and avoid violating
// the multi-column unique constraint on the table
const { resourceId: resourceIds = [''] } = webhook;
let records = [];
for (const resourceId of resourceIds) {
// update an existing record if one exists in the pending state, otherwise create a new entry
const record: pcc_webhook_update = await prismaClinical.pcc_webhook_update.upsert({
where: {
organization_id_facility_id_patient_id_resource_id_event_type_status: {
organization_id: webhook.orgId,
facility_id: webhook.facId,
patient_id: webhook.patientId,
resource_id: resourceId,
event_type: webhook.eventType,
status: 'pending'
}
},
update: {
webhook_date: new Date()
},
create: {
event_type: webhook.eventType,
organization_id: webhook.orgId,
facility_id: webhook.facId,
patient_id: webhook.patientId,
resource_id: resourceId,
status: 'pending' // not needed
}
});
records.push(record);
}
return records;
} catch (error) {
console.error(error);
}
};
/functions/handle-pcc-webhooks/handler.spec.ts
import fs from 'fs';
import path from 'path';
import MockDate from 'mockdate';
import { prismaClinicalMock } from '../../../testing/prisma-clinical-mock';
import { createAllergyAddRecord } from './__mocks__/allergy';
import { requestObject } from './handler.types';
import { handlePccWebhook } from './handler';
describe('allergy.add', () => {
let requestObject: requestObject;
let allergyAddRecord: any;
beforeAll(() => {
requestObject = getRequestObject('allergy.add');
});
beforeEach(() => {
MockDate.set(new Date('1/1/2022'));
allergyAddRecord = createAllergyAddRecord(new Date());
});
afterEach(() => {
MockDate.reset();
});
test('should create an allergy.add database entry', async() => {
prismaClinicalMock.pcc_webhook_update.create.mockResolvedValue(allergyAddRecord);
// this is where I would expect handlePccWebhook to return the newly created database
// record, but instead it returns undefined. If I run the function outside of this
// unit test, with the same input value, it functions perfectly
await expect(handlePccWebhook(requestObject)).resolves.toEqual([allergyAddRecord]);
});
});
// This just builds a request object with the current webhook being tested
function getRequestObject(webhookType: string) {
// read the contents of request object file as a buffer, then convert it to JSON
const rawRequestObject = fs.readFileSync(path.resolve(__dirname, '../../sample-data/handle-pcc-webhook-request.json'));
const requestObject: requestObject = JSON.parse(rawRequestObject.toString());
// read the contents of the webhook file as a buffer, then convert it to a string
const rawWebhook = fs.readFileSync(path.resolve(__dirname, `../../sample-data/${webhookType}.json`));
const webhookString = rawWebhook.toString();
// set the body of the request object to the contents of the target webhook
requestObject.body = webhookString;
return requestObject;
}
Finally, here is the result of running the unit test:
So after banging my had against the wall for a few hours, I figured out the issue. In my handler.spec.ts file, I had the following line:
prismaClinicalMock.pcc_webhook_update.create.mockResolvedValue(allergyAddRecord);
what that does is mock the value returned for any create functions run using Prisma. The issue is that my function is using an upsert function, which I wasn't explicitly mocking, thus returning undefined. I changed the above line to
prismaClinicalMock.pcc_webhook_update.upsert.mockResolvedValue(allergyAddRecord);
and it started working.
I have the sealed trait below and its case class and I would like to transform it into JSON to give it as a response in my Akka Http app.
sealed trait HttpRestError {
val statusCode: StatusCode
val code: String
val message: String
}
case class UnauthorizedError() extends HttpRestError {
override val statusCode: StatusCode = Unauthorized
override val code: String = "Unauthorized"
override val message: String = "Unauthorized"
}
And the Route part
def login2: Route = {
path("test") {
pathEndOrSingleSlash {
get {
onComplete(authService.testUser.toRestError[UnauthorizedError]) {
case util.Success(f) => f match {
case Left(error) =>
complete((error.statusCode, error))
case Right(v) => complete(OK -> v)
}
case util.Failure(ex) =>
complete(StatusCodes.InternalServerError)
}
}
}
}
}
The problem is that when the Either returns the Left side the response is empty, but the error code is correct.
Any idea?
How to evade this error: VM18193:27 Unable to open database ReferenceError: sqlitePlugin is not defined(…)
setTimeout(function() {
let db = new SQLite();
db.openDatabase({
name: "data.db",
location: "default"
}).then(() => {
db.executeSql("CREATE TABLE IF NOT EXISTS people (id INTEGER PRIMARY KEY AUTOINCREMENT, firstname TEXT, lastname TEXT)", {}).then((data) => {
console.log("TABLE CREATED: ", data);
}, (error) => {
console.error("Unable to execute sql", error);
})
}, (error) => {
console.error("Unable to open database", error);
});
}, 2000);
How can i execute some query?
if(SqlSettingsService.openDb){
this.db = SqlSettingsService.getDB();
this.db.executeSql("CREATE TABLE IF NOT EXISTS people (id INTEGER PRIMARY KEY AUTOINCREMENT, firstname TEXT, lastname TEXT", {}).then
instead i get error.
console:
SqlSettingsService() starts
VM21750:27 Unhandled Promise rejection: Cannot read property 'executeSql' of null ; Zone: <root> ; Task: Promise.then ; Value: TypeError: Cannot read property 'executeSql' of null(…) TypeError: Cannot read property 'executeSql' of null
The plugin sqlLite does not work in a browser, you can use Websql for the browser instead (with compatible browsers, including Chrome and Opera as far as I know).
Transactions written for Websql are compatible with transactions written for SQLite.
Here is a service I have done to manage the Connection to the DB and make it work regardless if the program runs in a browser or a on real device:
import { Injectable } from '#angular/core';
import { SQLite } from 'ionic-native';
import { Platform } from 'ionic-angular';
import { Storage } from '#ionic/storage';
#Injectable()
export class SqlSettingsService {
private db: any = null;
private isOpened: boolean = false;
constructor() {
console.log('SqlSettingsService() starts');
}
public getDB(){
return this.db;
}
public openDb = (platform:Platform,winSer:any):Promise<any> => {
console.log('SqlSettingsService() opend DB starts');
let p:Promise<any>;
if(!this.isOpened){
this.isOpened = true;
if(platform.is('core')){
this.db = winSer.window.openDatabase("ionic2BrowserDev","1.0","",5*1024*1024);
p = new Promise(function(resolve,reject){resolve('websql success')});
} else {
this.db = new SQLite();
p = this.db.openDatabase({
name: 'data.db',
location: 'default' // the location field is required
}).then(
()=>{console.log("SqlSettingsService open db successful")},
(err)=>{console.error(err)}
);
}
} else {
p = new Promise(function(resolve,reject){
resolve('db already opened');
});
}
return p;
}
public closeDb = () => {
this.isOpened = false;
return this.db.close();
}
}
winSer is another service to access the window Object that I use in my app.component.ts when I call openDB() on SqlSettingsService. It's just this:
import { Injectable } from '#angular/core';
#Injectable()
export class WindowService {
public window = window;
}
To execute query:
[SqlSettingsService-instance].openDb();
[SqlSettingsSevice-instance].getDB().transaction(
function(tx){
tx.executeSql([your sql],[bracket values you want to pass],success,error);
function success(tx,rs){
console.log("success exec sql: ")
console.info(rs);
}
function error(tx,error){
console.log('execSqlCustom error ' + error.message + " for tx " + tx);
}
});
I am new one in akka spray :)
I have this router actor:
class ProjectResource extends HttpServiceActor with DefaultJsonFormats {
import spray.http.MediaTypes.`application/json`
def receive = runRoute {
pathPrefix("rest" / "1.2") {
path("users" / Segment / "projects" / Segment / "auth_url") {
case (key, id) =>
get {
respondWithMediaType(`application/json`) {
requestContext =>
val responder = context actorOf Responder.props(sender(), requestContext)
context actorOf GetTask.props(key, id, responder)
}
}
}
}
}
}
and responder:
class Responder(replyTo: ActorRef, ctx: RequestContext) extends Actor with DefaultJsonFormats {
implicit val authFormat = jsonFormat2(AuthDTO)
def receive = {
case x: AuthDTO =>
ctx.complete(200, x)
context stop self
}
}
and when i tried to
curl -v http://localhost:8080/rest/1.2/users/123/projects/1/auth_url
i got this error (on ctx.complete(200, x) string ...):
[ERROR] [07/11/2016 18:40:32.954] [default-akka.actor.default-dispatcher-3] [akka://default/user/projectResource] Error during processing of request HttpRequest(GET,http://localhost:8080/rest/1.2/users/123/projects/1/auth_url,List(User-Agent: curl/7.35.0, Host: localhost:8080),Empty,HTTP/1.1)
java.lang.IllegalArgumentException: requirement failed
What i am doing wrong? Help Please!
How can i respond back with a text file containing json data upon request from client .
The request url is:
http://localhost:8082/web/ws/datafileid/json/Sat May 16 12:05:07 IST 2015.txt/
Controller code that handles the request is:
#RequestMapping(value=EmpRestURIConstants.DATAFILE_REQUEST,method=RequestMethod.GET)
#ResponseBody
public String datafileresponse(#PathVariable("filename") String filename, HttpServletResponse response) {
return cinehomeRestService.checkfilevalid(filename);
}
Service class that handles the request to check the file exists is:
#Override
public String checkfilevalid(String filename) {
String datafilename=webServiceDao.getdatafilename();
JSONObject obj = new JSONObject();
if(datafilename.equals(filename)) {
return "file";
}
else {
try {
obj.put("status", "022");
} catch (JSONException e) {
e.printStackTrace();
}
return obj.toString();
}
}
Here I need to respond back with the datafile.txt that exists at location resources. How can I perform the task. Can anyone help?
i have tried a method
#RequestMapping(value=EmpRestURIConstants.DATAFILE_REQUEST,method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE)
public #ResponseBody Response datafileresponse(#PathVariable("filename")String filename) throws IOException{
JSONObject readdata = new JSONObject();
String uploadPath = servletContext.getRealPath("");
String fullyqualifiedfilename=uploadPath+filename;
System.out.println("+++++++++"+fullyqualifiedfilename);
return Response.ok(uploadPath)
.header("Content-Disposition", "attachment; filename=\"" + fullyqualifiedfilename + "\"" ) //optional
.build();
}
i GOT THE REPLY AS...
{ "statusType": "OK", "entity": /home/cine/WORKSPACES/study/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/
"entityType": "java.lang.String", "metadata": { "Content-Disposition": [ "attachment;
filename="/home/cine/WORKSPACES/study/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/Cine Sat May 16 12:05:07 IST 2015.txt"" ] }, "status": 200 }
What this status means. Does the client can fetch teh file using this response.??