http requests with dart - dart

I am trying to learn dart, experimenting with http requests from this blog.
So I installed dart on Windows but for whatever reason I cant seem to run this script:
import 'dart:html';
import 'dart:convert';
void main() {
var data = { 'title' : 'My first post' };
HttpRequest.request(
'https://jsonplaceholder.typicode.com/posts',
method: 'POST',
sendData: json.encode(data),
requestHeaders: {
'Content-Type': 'application/json; charset=UTF-8'
}
)
.then((resp) {
print(resp.responseUrl);
print(resp.responseText);
});
}
// Response
// https://jsonplaceholder.typicode.com/posts
// { "title": "My first post", "id": "101" }
When I run this from Windows terminal $dart run script.dart this will error:
script.dart:1:8: Error: Not found: 'dart:html'
import 'dart:html';
^
script.dart:8:3: Error: Undefined name 'HttpRequest'.
HttpRequest.request(
^^^^^^^^^^^
But in the blog post there is a link to dart pad where the code runs just fine. Any ideas to try? Thanks for any incite
$dart --version
Dart SDK version: 2.15.1 (stable) (Tue Dec 14 13:32:21 2021 +0100) on "windows_x64"

Using the http package, is the preferred approach since it will work consistently on all platforms.
The same request can be made by doing the following:
import 'dart:convert';
import 'package:http/http.dart' as http;
void main() {
var data = {'title': 'My first post'};
http.post(
Uri.parse('https://jsonplaceholder.typicode.com/posts'),
headers: {'Content-Type': 'application/json; charset=UTF-8'},
body: json.encode(data),
).then((resp) {
print(resp.body);
});
}
Although typically async/await syntax is used instead:
import 'dart:convert';
import 'package:http/http.dart' as http;
void main() async {
var data = {'title': 'My first post'};
var resp = await http.post(
Uri.parse('https://jsonplaceholder.typicode.com/posts'),
headers: {'Content-Type': 'application/json; charset=UTF-8'},
body: json.encode(data),
);
print(resp.body);
}

Related

CDK GraphqlApi with Function Using Typescript Causes Undefined or Not Exported

I have a aws_appsync.GraphqlApi with a lambda resolver:
import * as cdk from 'aws-cdk-lib';
import {aws_appsync} from 'aws-cdk-lib';
import {Construct} from 'constructs';
import {AttributeType, BillingMode, Table} from "aws-cdk-lib/aws-dynamodb";
import * as path from "path";
import {FieldLogLevel} from "aws-cdk-lib/aws-appsync";
import {RetentionDays} from "aws-cdk-lib/aws-logs";
import {Code, Function, Runtime} from "aws-cdk-lib/aws-lambda";
export class RelmStack extends cdk.Stack {
constructor(scope: Construct, id: string, props?: cdk.StackProps) {
super(scope, id, props);
const relmTable = new Table(this, 'relm', {
billingMode: BillingMode.PAY_PER_REQUEST,
tableName: 'relm',
partitionKey: {
name: 'pk',
type: AttributeType.STRING
}, sortKey: {
name: 'sk',
type: AttributeType.STRING
}
})
const api = new aws_appsync.GraphqlApi(this, 'relm-api', {
name: 'relm-api',
logConfig: {
fieldLogLevel: FieldLogLevel.ALL,
excludeVerboseContent: true,
retention: RetentionDays.TWO_WEEKS
},
schema: aws_appsync.SchemaFile.fromAsset(path.join(__dirname, 'schema.graphql')),
authorizationConfig: {
defaultAuthorization: {
authorizationType: aws_appsync.AuthorizationType.API_KEY,
apiKeyConfig: {
name: 'relm-api-key'
}
}
}
})
const createLambda = new Function(this, 'dialog-create', {
functionName: 'dialog-create',
runtime: Runtime.NODEJS_14_X,
handler: 'index.handler',
code: Code.fromAsset('src/lambda'),
memorySize: 3008,
})
const createDataSource = api.addLambdaDataSource('create-data-source', createLambda)
createDataSource.createResolver('create-resolver', {
typeName: 'Mutation',
fieldName: 'dialogCreate'
});
relmTable.grantWriteData(createLambda);
}
}
The sources lives under src/lambda/index.ts and the code is as follows:
exports.handler = async (event: any) => {
console.log('event: ', event)
};
Super simple. When the file extension is index.js everything works. When I change it to index.ts I get an error:
"index.handler is undefined or not exported"
I've looked at many examples on how to do this and all of them seem to be using the ts extension with no problems. What am I doing wrong here?
You should use the NodejsFunction which includes transpiling TypeScript to JavaScript.
https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_lambda_nodejs-readme.html
You can write your handler in typescript but you'll have to invoke a build script to transpile it into javascript to serve as your lambda handler.
This project uses cdk and tsc:
https://github.com/mavi888/cdk-typescript-lambda/blob/main/package.json
This line discusses using esbuild to transpile:
https://docs.aws.amazon.com/lambda/latest/dg/typescript-package.html

Is there any solution for verifyPurchase in In-app-Purchase for ios flutter

I am implementing In-app purchases in my flutter app, there is the last step to verify the purchase by making a cloud function named to verify the purchase. I made a function and deployed it successfully to firebase but when I am testing this function in postman I got an error of bad request also when I use this function in the flutter app I got false each time.
Please help me do this accurately or recommend any tutorial/article.
I tried to implement cloud function in two ways. first one is here
import * as admin from "firebase-admin";
import * as Functions from "firebase-functions";
import {CLOUD_REGION,PURCHASE_TOKEN } from "./constants";
import fetch from 'node-fetch';
const functions = Functions.region(CLOUD_REGION);
admin.initializeApp();
export const verifyPurchase = functions.https.onCall(
async (
context,
): Promise<any> => {
const response = await fetch("https://buy.itunes.apple.com/verifyReceipt", {
method: 'POST',
body: JSON.stringify({
"receipt-data": PURCHASE_TOKEN,
"password": PURCHASE_PASSWORD
"exclude-old-transactions": true,
}),
headers: {
'Content-Type': 'application/json',
Accept: '/',
},
});
if(response.ok){
return response.body;
}else {
return response.error;
}
});
while test on postman getting this response
{
"result": {
"size": 0,
"timeout": 0
}
}

Axios Post returning no data after 200 response

I am playing around with React (I'm a newbie) and trying to make a post request to my rails API (on localhost atm). I wrote the post function to also console.log my response and I consistently get a 200 response, confirming that the object has been successfully created in my API. However, I want to look through my http response to confirm that the correct parameters have been passed through and it seems that there is no body. Not sure if I am missing in my post request or if I am updating my state incorrectly after I make the post request.
My React Component
import React, { Component } from 'react';
import axios from 'axios'
import update from 'immutability-helper'
import BusinessForm from './businessForm'
const API = 'http://localhost:3001/api/v1/businesses/'
class NewBusinesses extends Component {
state = {
businesses: [],
editID: null
}
check = () => {
console.log(this.state.businesses)
}
addNew = () => {
axios.post(
API,
{
business:
{ name: 'NEW BUSINESS',
address: '',
city: '',
zip: '',
wifi: '',
phone: '',
bathroom: ''
}
}
)
.then(response => {
console.log(response)
const businesses = update(this.state.businesses, {
$splice: [[0,0,response.data]]
})
this.setState({businesses: businesses,
editID: response.data.id})
})
.catch(error => console.log(error))
}
Console after I onClick the function (console.log(response))
{data: "", status: 200, statusText: "OK", headers: {…}, config: {…}, …}
config:{adapter: ƒ, transformRequest: {…}, transformResponse: {…}, timeout: 0, xsrfCookieName: "XSRF-TOKEN", …}
data:""
headers:
{content-type: "text/html", cache-control: "no-cache"}
request
:
XMLHttpRequest {onreadystatechange: ƒ, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …}
status:200
statusText:"OK"
__proto__:Object
Nevermind! This issue was on the API side not due to anything I did in my React app. I had to add the line
render json:#business
to my create method in my Rails API

how to import html files with webpack 2?

I can't figure out how to import html files with webpack 2! I am using angular 1.6.0 and typescript.
I would like to import a template and use it as a router state template:
import * as angular from 'angular';
import * as uiRouter from 'angular-ui-router';
import theView from './theView.html';
import appComp from './app.component';
export default angular
.module('app.main', [uiRouter])
.component('myAppComp', appComp)
.config(($stateProvider, $urlRouterProvider, $locationProvider) => {
'ngInject';
$locationProvider.hashPrefix('');
$stateProvider
.state('main', {
url: '/main',
template: '<p>main state template</p>'
})
.state('main.cardList', {
url: '/cardList',
template: theView
});
}
It gives:
error:
ERROR in ./src/app/module.ts
(3,22): error TS2307: Cannot find module './theView.html'.
What (wierd) I don't understand is if I import the template same as above and use it in a component template, it does gives same error "cannot find module './theView.html'" but it works!
This works (with ts compilation error):
import template from './theView.html';
.component(appComp, {
template
})
webpack.config:
module.exports = {
entry: './src/app/module.ts',
module: {
rules: [
{
test: /\.tsx?$/,
loader: 'ts-loader',
exclude: /node_modules/
},
{
test: /\.html$/,
use: [{ loader: 'html-loader' }]
}
]
},
output: {
filename: 'bundle.js',
path: __dirname + "/dist"
}
};
What is going on here..?
For the people who can come across this problem in the future; it is solved as follows:
declare const require: any;
$stateProvider
.state('main.cardList', {
url: '/cardList',
template: require('./theView.html').default
});
Credits to #yadejo for the answer above!

Create an Http injectable in an Angular2 service?

I'm trying to wrap http in a service, so that all db access is passing through my channel
the issue is, services cannot have injectables passed to their constructor (right?) so I have to construct it all myself. I'm using the code:
import {Http,HTTP_BINDINGS,XHRBackend,BaseRequestOptions} from 'http/http';
import {Injector,bind} from 'angular2/di'
...
var injector = Injector.resolveAndCreate([
BaseRequestOptions,
XHRBackend,
bind(Http).toFactory(
function(backend, defaultOptions) {
return new Http(backend, defaultOptions);
},
[XHRBackend, BaseRequestOptions])
]);
this.http = injector.get(Http);
but when trying to use it by:
this.http.get('./entities.json')
//Get the RxJS Subject
.toRx()
// Call map on the response observable to get the parsed people object
.map(res => res.json())
.subscribe(e => this.entities = e);
I get an error:
Error during instantiation of DBDriver! (Entities -> DBDriver).
angular2.dev.js:22367 ORIGINAL EXCEPTION: No provider for function () {}! (function (_backend, _defaultOptions) { -> function (_browserXHR, _baseResponseOptions) { -> function () {})
Make sure that HTTP is injected in your service
Note #Inject(http) at de service constructor
#Inject(Http) public http: Http
Note that http, at least at angular2 alpha45, is outside angular lib, therefore you have to manually add http lib
<script src="/node_modules/angular2/bundles/angular2.min.js"></script>
<script src="/node_modules/angular2/bundles/http.min.js"></script>
SERVICE
import {Http, Headers, HTTP_BINDINGS} from 'angular2/http';
import {Inject} from 'angular2/angular2'
constructor(#Inject(Http) public http: Http) {}
getQuote(): Promise<any> {
return new Promise((resolve, reject) => {
this.http.get('http://localhost:3001/api/random-quote')
.map(res => res.text())
.subscribe(
data => resolve(data),
err => this.logError(err),
() => console.log("Random Quote Complete")
);
})
}
COMPONENT
import {Component, bootstrap, CORE_DIRECTIVES} from 'angular2/angular2';
import {Http, Headers, HTTP_BINDINGS} from 'angular2/http';
import {ChuckService} from "./chuck-service";
#Component({
selector: 'hello-app',
template: `
{{quoteOfTheDay}}<br />
<button (click) = "getQuote()">Get new quote</button><br /><br />
`,
directives: [CORE_DIRECTIVES],
providers: [ChuckService, HTTP_BINDINGS]
})
export class HelloApp {
quoteOfTheDay: string = '';
constructor(public _chuckService: ChuckService) {
}
getQuote(){
this._chuckService.getQuote().then((resp) => this.quoteOfTheDay = resp);
}
}
bootstrap(HelloApp);
INDEX.HTML
<script src="/node_modules/es6-shim/es6-shim.min.js"></script>
<script src="/node_modules/systemjs/dist/system-csp-production.js"></script>

Resources