got confused in loopback - node.js

hello guys i m new to loopback so please, can anyone help me with this following this
1. i know how to render html page from loopback server for eg:-
<form method="post" action="register">
<input type="text" name="name">
<input type="text" name="lastname">
</form>
how to can request name or lastname in my model user
'use strict';
module.exports = function(User) {
// how i can receive requested of name or lastname for eg :-
console.log(req.name)
};
2.how i can insert this data to my postgres table(table name :-register) in column "name"
3.last one is that how to differentiate table name and model name using automigrate

module.exports = function(User) {
User.show = function(name,lastName) {
console.log(name);
console.log(lastName);
}
User.remoteMethod('show', {
accepts: [
{ arg: 'name', type: 'string' },
{ arg: 'lastName', type: 'string' }
],
returns: {arg: 'result', type: 'string'}
});
}
for the insert something like :
var yourVar = name;
pg.connect(dbUrl, function(err, client, done) {
client.query(
'INSERT into yourTable(name) VALUES ($1)',
['title'],
function(err, result) {
if (err) {
console.log(err);
} else {
console.log('row inserted');
}
});
});
depending on your table and log credentials
Edit :
to use auto migrate, you must first :
create a data source in /server/datasources.json :
"mydb": {
"name": "mydb",
"connector": "postgresql"
}
Connect to UNIX domain socket in /var/run/postgresql/.s.PGSQL.5432 :
{
"postgres": {
"host": "/var/run/postgresql/",
"port": "5432",
"database": "dbname",
"username": "dbuser",
"password": "dbpassword",
"name": "postgres",
"debug": true,
"connector": "postgresql"
}
}
define your models in /common/models/model.json, it shoud look like this :
var schema={
"name": "User",
"options": {
"idInjection": true,
"postgresql": {
"schema": "yourShema",
"table": "USER"
}
},
"properties": {
"id": {
"type": "Number",
"required": true,
"length": 64,
"precision": null,
"scale": null,
"postgresql": {
"columnName": "id",
"dataType": "integer",
"dataLength": 64,
"dataPrecision": null,
"dataScale": null,
"nullable": "NO"
}
},
"name": {
"type": "String",
"required": false,
"length": 40,
"precision": null,
"scale": null,
"postgresql": {
"columnName": "name",
"dataType": "character varying",
"dataLength": 40,
"dataPrecision": null,
"dataScale": null,
"nullable": "YES"
}
},
"lastName": {
"type": "String",
"required": false,
"length": 40,
"precision": null,
"scale": null,
"postgresql": {
"columnName": "lastName",
"dataType": "character varying",
"dataLength": 40,
"dataPrecision": null,
"dataScale": null,
"nullable": "YES"
}
}
}
then you must call Model.automigrate() or Model.autoupdate() in your code like this :
ds.createModel(schema);
ds.autoupdate(schema) {
ds.discoverModelProperties('USER', function (err, props) {
console.log(props);
});
});
You will certainly have yo change some things but I hope you will achieve what you want ;)

Related

Creating Custom Account for Stripe

I tried creating Stripe Custom account on test mode
Request
const createAccountTeacher = catchAsync(async (req, res) =>
{
const date = new Date();
let time = Math.floor(date.getTime() / 1000);
const email = req.body.email;
const country = req.body.country;
const createAccount = await stripe.accounts.create({
type: 'custom',
country: country,
business_type: 'individual',
tos_acceptance: {
date: time,
ip: '8.8.8.8',
},
business_profile: {
mcc: '5734',
url: 'http://google.com',
product_description: 'Good Product',
support_phone: '12345567',
product_description: 'Teaching Courses available',
support_phone: '+10000000000',
},
individual: {
first_name: 'ABC',
last_name: 'XYZ',
dob: {
day: 24,
month: 6,
year: 1992,
},
address: {
line1: '1996 W Highland Ave',
postal_code: 90002,
city: ' San Bernardino',
state: 'California',
},
email: email,
phone: '+1202-555-0454',
ssn_last_4: 9999,
id_number: 123459999,
},
external_account: {
object: 'bank_account',
country: 'US',
currency: 'usd',
account_number: '000123456789',
routing_number: 121000358,
},
capabilities: {
card_payments: { requested: true },
transfers: { requested: true },
},
});
if (createAccount) {
res.status(200).json({ data: createAccount });
}
});
Here as response
{
"data":
{
"details_submitted": true,
"type": "custom",
"metadata": {},
"id": "acct_1LNcOTD4Ev4rC234",
"object": "account",
"default_currency": "usd",
"capabilities": {
"transfers": "pending",
"card_payments": "pending"
},
"business_type": "individual",
"individual": {
"metadata": {},
"id": "person_1LNcOVD4Ev4rC234OQjvuHiP",
"object": "person",
"account": "acct_1LNcOTD4Ev4rC234",
"dob": {
"year": 1992,
"day": 24,
"month": 6
},
"requirements": {
"currently_due": [],
"past_due": [],
"eventually_due": [],
"pending_verification": [
"id_number",
"verification.document"
],
"errors": [],
"alternatives": []
},
"ssn_last_4_provided": true,
"phone": "+12025550454",
"relationship": {
"percent_ownership": null,
"title": null,
"owner": false,
"director": false,
"representative": true,
"executive": false
},
"future_requirements": {
"currently_due": [],
"past_due": [],
"eventually_due": [],
"pending_verification": [],
"errors": [],
"alternatives": []
},
"verification": {
"status": "pending",
"details": null,
"document": {
"details_code": null,
"front": null,
"details": null,
"back": null
},
"additional_document": {
"details_code": null,
"front": null,
"details": null,
"back": null
},
"details_code": null
},
"address": {
"line2": null,
"line1": "1996 W Highland Ave",
"state": "California",
"postal_code": "90002",
"city": " San Bernardino",
"country": "US"
},
"email": "lilypota#ema-sofia.eu",
"created": 1658321573,
"first_name": "ABC",
"id_number_provided": true,
"last_name": "XYZ"
},
"charges_enabled": false,
"settings": {
"dashboard": {
"display_name": "Google",
"timezone": "Etc/UTC"
},
"payouts": {
"debit_negative_balances": false,
"statement_descriptor": null,
"schedule": {
"interval": "daily",
"delay_days": 2
}
},
"card_issuing": {
"tos_acceptance": {
"ip": null,
"date": null
}
},
"bacs_debit_payments": {},
"payments": {
"statement_descriptor_kanji": null,
"statement_descriptor_kana": null,
"statement_descriptor": "GOOGLE.COM"
},
"sepa_debit_payments": {},
"card_payments": {
"statement_descriptor_prefix_kanji": null,
"statement_descriptor_prefix": null,
"statement_descriptor_prefix_kana": null,
"decline_on": {
"avs_failure": false,
"cvc_failure": false
}
},
"branding": {
"icon": null,
"secondary_color": null,
"logo": null,
"primary_color": null
}
},
"tos_acceptance": {
"ip": "8.8.8.8",
"user_agent": null,
"date": 1658321567
},
"requirements": {
"current_deadline": null,
"past_due": [],
"errors": [],
"disabled_reason": "requirements.pending_verification",
"pending_verification": [
"individual.id_number",
"individual.verification.document"
],
"currently_due": [],
"eventually_due": [],
"alternatives": []
},
"payouts_enabled": false,
"company": {
"tax_id_provided": false,
"phone": "+12025550454",
"owners_provided": true,
"verification": {
"document": {
"details_code": null,
"front": null,
"details": null,
"back": null
}
},
"address": {
"line2": null,
"line1": "1996 W Highland Ave",
"state": "California",
"postal_code": "90002",
"city": " San Bernardino",
"country": "US"
},
"executives_provided": true,
"directors_provided": true,
"name": null
},
"external_accounts": {
"has_more": false,
"total_count": 1,
"object": "list",
"url": "/v1/accounts/acct_1LNcOTD4Ev4rC234/external_accounts",
"data": [
{
"last4": "6789",
"account_holder_name": null,
"metadata": {},
"id": "ba_1LNcOUD4Ev4rC234XwzzfiqR",
"object": "bank_account",
"account_type": null,
"default_for_currency": true,
"account_holder_type": null,
"account": "acct_1LNcOTD4Ev4rC234",
"status": "new",
"available_payout_methods": [
"standard"
],
"bank_name": "BANK OF AMERICA, N.A.",
"currency": "usd",
"country": "US",
"routing_number": "121000358",
"fingerprint": "gqPBt6FUMZJkqc9q"
}
]
},
"future_requirements": {
"current_deadline": null,
"past_due": [],
"errors": [],
"disabled_reason": null,
"pending_verification": [],
"currently_due": [],
"eventually_due": [],
"alternatives": []
},
"country": "US",
"email": null,
"created": 1658321576,
"business_profile": {
"support_email": null,
"product_description": "Teaching Courses available",
"mcc": "5734",
"support_url": null,
"support_address": null,
"url": "http://google.com",
"support_phone": "+10000000000",
"name": null
}
}
}
Custom Account is created but the problem it is restricted because of identity document
I am trying to upload the document like this
const updateAccount = catchAsync(async (req, res) => {
// let imagepath = ${req.protocol}://${req.get('host')}/uploads/${req.file.filename};
if(req.file.path){
const file = await stripe.files.create({
purpose: 'identity_document',
file: {
data: fs.readFileSync(req.file.path),
name: req.file.filename,
type: 'application/octet-stream',
},
}, {
stripeAccount: 'acct_1LNcOTD4Ev4rC234',
});
if(file){
res.status(200).json({data:file})
}
}
})
Still the custom account is restricted.
I would appreciate little help.

in apollo client pagination configuration with "merge" function, existing cached data always is empty even after calling fetchMore

I'm new to Apollo Client and I'm trying to implement pagination for my product list. but I can't figure out why the existing parameter in the merge function always returns empty. my incoming parameter always updates with a new list each time I call fetchMore but the existing parameter always is empty That's why I can't merge the new list with the old one.
this is my client configuration:
/* eslint-disable #typescript-eslint/no-unsafe-return */
import { ApolloClient, InMemoryCache } from '#apollo/client'
import { AppEndpoints } from './const'
import { createLink } from './links'
const cache = new InMemoryCache({
typePolicies: {
ListProductSearchType: {
fields: {
items: {
keyArgs: false,
// eslint-disable-next-line prefer-arrow/prefer-arrow-functions
merge: (existing = [], incoming, { args }) => {
console.log('>>>args', args)
console.log('>>>existing', existing) // it's always empty
console.log('>>>incoming', incoming)
return [...existing, ...incoming]
},
},
},
},
},
})
const link = createLink(AppEndpoints.main)
const client = new ApolloClient({
cache,
// ssrMode: false,
link,
defaultOptions: {
mutate: {
errorPolicy: 'ignore',
},
query: {
fetchPolicy: 'cache-first',
},
},
})
export default client
this is my Graphql response:
{
"data": {
"productSearch": {
"listDto": {
"count": 10,
"items": [
{
"id": "1d37d4fe-79d9-440a-8869-2dca0327791b",
"code": "780133 Iceland Poppy",
"isMyfavorite": false,
"currency": "$",
"imageUrl": "https://devcdn.sonbol.nl/Product/flower.jpg",
"price": 429.29,
"compareAtPrice": 240.4,
"hasDiscount": true,
"visited": 27685,
"salesCount": 8148,
"createdDateTime": "2020-12-14T06:02:38.0469339+00:00",
"__typename": "ProductSearchDto"
},
{
"id": "ae15c925-75ef-4dde-aa07-0eeb1bbb75c8",
"code": "330338 Amaranth",
"isMyfavorite": false,
"currency": "$",
"imageUrl": "https://devcdn.sonbol.nl/Product/flower.jpg",
"price": 234.8,
"compareAtPrice": 211.32,
"hasDiscount": true,
"visited": 27660,
"salesCount": 6374,
"createdDateTime": "2020-12-05T15:04:37.4237772+00:00",
"__typename": "ProductSearchDto"
},
{
"id": "de23a1f8-5e79-4cf9-88f0-57518c42a82c",
"code": "690156 Snowflake",
"isMyfavorite": false,
"currency": "$",
"imageUrl": "https://devcdn.sonbol.nl/Product/flower.jpg",
"price": 110.11,
"compareAtPrice": 88.09,
"hasDiscount": true,
"visited": 27141,
"salesCount": 2278,
"createdDateTime": "2020-10-18T11:27:38.0467775+00:00",
"__typename": "ProductSearchDto"
},
{
"id": "fb298a9c-a3d7-4c0e-a96e-a552b98d340f",
"code": "375033 Peony",
"isMyfavorite": false,
"currency": "$",
"imageUrl": "https://devcdn.sonbol.nl/Product/flower.jpg",
"price": 337.68,
"compareAtPrice": 151.96,
"hasDiscount": true,
"visited": 27050,
"salesCount": 2483,
"createdDateTime": "2020-12-06T22:57:37.4236274+00:00",
"__typename": "ProductSearchDto"
},
{
"id": "d017638f-3062-49bf-99cc-0e06ba0882b9",
"code": "112093 Hyacinth, wild",
"isMyfavorite": false,
"currency": "$",
"imageUrl": "https://devcdn.sonbol.nl/Product/flower.jpg",
"price": 460.43,
"compareAtPrice": 326.91,
"hasDiscount": true,
"visited": 26843,
"salesCount": 530,
"createdDateTime": "2020-11-10T23:13:37.4235865+00:00",
"__typename": "ProductSearchDto"
},
{
"id": "682a3c04-a462-4cbd-be8f-8b65d024b73f",
"code": "914276 Iceland Poppy",
"isMyfavorite": false,
"currency": "$",
"imageUrl": "https://devcdn.sonbol.nl/Product/flower.jpg",
"price": 126.81,
"compareAtPrice": 100.18,
"hasDiscount": true,
"visited": 24055,
"salesCount": 6328,
"createdDateTime": "2021-01-05T11:05:38.0469862+00:00",
"__typename": "ProductSearchDto"
},
{
"id": "c48819e2-52f4-4324-9f11-616efbc1a744",
"code": "494847 Persian Candytuft",
"isMyfavorite": false,
"currency": "$",
"imageUrl": "https://devcdn.sonbol.nl/Product/flower.jpg",
"price": 405.95,
"compareAtPrice": 288.22,
"hasDiscount": true,
"visited": 23713,
"salesCount": 7474,
"createdDateTime": "2020-10-23T16:24:37.4236199+00:00",
"__typename": "ProductSearchDto"
},
{
"id": "7118ddd5-56cf-4e12-9665-accb5abf3f73",
"code": "682251 Violet",
"isMyfavorite": false,
"currency": "$",
"imageUrl": "https://devcdn.sonbol.nl/Product/flower.jpg",
"price": 184.09,
"compareAtPrice": 90.2,
"hasDiscount": true,
"visited": 23448,
"salesCount": 6196,
"createdDateTime": "2020-10-12T08:36:38.0469107+00:00",
"__typename": "ProductSearchDto"
},
{
"id": "9e69b51a-560e-4d5e-b956-d9438d996c61",
"code": "982376 Calendula",
"isMyfavorite": false,
"currency": "$",
"imageUrl": "https://devcdn.sonbol.nl/Product/flower.jpg",
"price": 62.25,
"compareAtPrice": 38.6,
"hasDiscount": true,
"visited": 23300,
"salesCount": 9072,
"createdDateTime": "2020-10-10T14:24:38.0463778+00:00",
"__typename": "ProductSearchDto"
},
{
"id": "623dde57-8daf-4637-b2d3-0ebbf166aad0",
"code": "138453 Manchineel",
"isMyfavorite": false,
"currency": "$",
"imageUrl": "https://devcdn.sonbol.nl/Product/flower.jpg",
"price": 121.92,
"compareAtPrice": 56.08,
"hasDiscount": true,
"visited": 22373,
"salesCount": 4735,
"createdDateTime": "2020-10-11T12:04:37.4235489+00:00",
"__typename": "ProductSearchDto"
}
],
"__typename": "ListProductSearchType"
},
"__typename": "GenericQueryResponseProductSearchType"
}
}
}
and this is my query:
export const GetProductSearchDocument = /*#__PURE__*/ gql`
query GetProductSearch($filter: GenericFilterRequestProductSearchReqInputType!) {
productSearch(filter: $filter) {
listDto {
count
items {
id
code
isMyfavorite
currency
imageUrl
price
compareAtPrice
hasDiscount
visited
salesCount
createdDateTime
}
}
}
}
i'm calling fetchMore like this:
const [pageIndex, setpageIndex] = useState(0)
const { productResults, loading, fetchMore } = useQueryProductSearchData()
// eslint-disable-next-line #typescript-eslint/unbound-method
const { formatMessage } = useIntl()
useEffect(() => {
if (pageIndex !== 0) {
fetchMore({
variables: {
filter: {
pageSize: 10,
pageIndex,
dto: {
filters: [],
},
},
},
})
}
}, [fetchMore, pageIndex])
const onViewMore = () => {
setpageIndex((pre: any) => pre + 1)
}
Try adding keyFields: [], like:
typePolicies: {
ListProductSearchType: {
keyFields: [],
fields: {
items: {
keyArgs: false,
// eslint-disable-next-line prefer-arrow/prefer-arrow-functions
merge: (existing = [], incoming, { args }) => {
console.log('>>>args', args)
console.log('>>>existing', existing) // it's always empty
console.log('>>>incoming', incoming)
return [...existing, ...incoming]
},
},
},
},
},
You should add read function to your field policy
const cache = new InMemoryCache({
typePolicies: {
ListProductSearchType: {
fields: {
items: {
//your code here
//then add this function
read(existing) {
return existing
},
},
},
},
},
})

I can't set unique field in Loopback ORM model

I'm new in Loopback 3.
And I need to define the model with the unique field.
Email field should be unique. I'm using Postgresql as DB.
I have tried adding "unique": true option. Also, I have tried to follow these pieces of advice: Ensure unique field value in loopback model. But it didn't give the desired result.
"properties": {
"id": {
"type": "number",
"id": true,
"generated": true,
"postgresql": {
"dataType": "bigint"
}
},
"name": {
"type": "string",
"postgresql": {
"dataType": "character varying"
}
},
"email": {
"type": "varchar",
"postgresql": {
"dataType": "character varying"
}
},
"added_date": {
"type": "date",
"postgresql": {
"dataType": "date"
}
}
}
In the end result, I want to have a unique field in Postgres scheme.
It should look like this in Postgres :
-- Table: public."user"
-- DROP TABLE public."user";
CREATE TABLE public."user"
(
id bigint NOT NULL DEFAULT nextval('user_id_seq'::regclass),
name character varying COLLATE pg_catalog."default",
email character varying COLLATE pg_catalog."default",
added_date date,
CONSTRAINT user_pkey PRIMARY KEY (id),
CONSTRAINT user_email_key UNIQUE (email)
)
WITH (
OIDS = FALSE
)
TABLESPACE pg_default;
ALTER TABLE public."user"
OWNER to postgres;
I think these will work. Either add the index property to the column def, or add it to the indexes portion of the model. It's weird there isn't more documentation on this.
"properties": {
"id": {
"type": "number",
"id": true,
"generated": true,
"postgresql": {
"dataType": "bigint"
}
},
"name": {
"type": "string",
"postgresql": {
"dataType": "character varying"
}
},
"email": {
"type": "varchar",
"postgresql": {
"dataType": "character varying"
}
},
"added_date": {
"type": "date",
"postgresql": {
"dataType": "date"
}
}
},
"indexes": {
"EMAIL_INDEX": {
"columns": "email",
"kind": "unique"
}
}
Or alternatively
"properties": {
"id": {
"type": "number",
"id": true,
"generated": true,
"postgresql": {
"dataType": "bigint"
}
},
"name": {
"type": "string",
"postgresql": {
"dataType": "character varying"
}
},
"email": {
"type": "varchar",
"postgresql": {
"dataType": "character varying"
},
"index": {"kind": "UNIQUE"}
},
"added_date": {
"type": "date",
"postgresql": {
"dataType": "date"
}
}
}

Mongoose find document by key whose value is a complex object

I am using Mongoose to do a search for documents in a collection based on the criteria described below:
Document:
{
"_id": {
"$oid": "5a60621e20205641281f7c2f"
},
"key1": [
{
"available": true,
"required": true,
"name": "Name-1"
},
{
"available": true,
"required": true,
"name": "Name-2"
},
{
"available": true,
"required": true,
"name": "Name-3"
}
],
"__v": 0
}
I want to perform a search based on property key1. So basically what I want to do is pass the json object as search pattern below and get the result as the document above in return
[
{
"available": true,
"required": true,
"name": "Name-1"
},
{
"available": true,
"required": true,
"name": "Name-2"
},
{
"available": true,
"required": true,
"name": "Name-3"
}
]
Is there a way that I can achieve this?
You can check $eq in mongodb docs $eq.
const selector = [
{
"available": true,
"required": true,
"name": "Name-1"
},
{
"available": true,
"required": true,
"name": "Name-2"
},
{
"available": true,
"required": true,
"name": "Name-3"
}
];
Model.find({key1: {$eq: selector}}, (error, result) => {
if(!err) {
res.send(result);
}
});
Model is the collection you fetch from.

Using build in model accessToken not working in loopback

I'm trying to begin programming an api for an android application and wanted to use node.js + loopback for this. But I'm running into some trouble testing/ learning the language.
Following code should generate new users in my database(and it does) but when I try to login with this user no AccessToken in created an printen to the console. Any idea what I'm doing wrong?
My Test code: create-test-data.js
var app = require('./app');
var dataSource = app.dataSources.mysql;
var loopback = require('loopback');
var User = loopback.User; // Getting User Model
var AccessToken = loopback.AccessToken; // Getting AccessTokenModel
/*
Initializing the database done by this. If already exist it will clean it.
dataSource.automigrate('user', function (err) {});
dataSource.automigrate('account', function (err) {});
dataSource.automigrate('accesstoken', function (err) {});
*/
//Creating some users in mysql database
User.create({username: 'timbo', email: 'test#gmail.com', password: 'monkey123'} , function(err, user) {console.log(user);});
User.create({username: 'timbo2', email: 'test2#gmail.com', password: 'monkey123'} , function(err,user) {console.log(user);});
User.create({username: 'timbo3', email: 'test3#gmail.com', password: 'monkey123'} , function(err,user) {console.log(user);});
User.login({username: 'timbo', password: 'monkey123'}, function(err, accesstoken) {console.log("This is the token: " + accesstoken);});
//No accesstoken created / saved in the database
datasource.json
{
"db": {
"defaultForType": "db",
"connector": "mysql",
"host": "127.0.0.1",
"database": "test",
"user": "root",
"password": "warcraft"
},
"push": {
"defaultForType": "push",
"connector": "loopback-push-notification",
"installation": "installation",
"notification": "notification",
"application": "application"
},
"mail": {
"defaultForType": "mail",
"connector": "mail"
},
"mysql": {
"connector": "mysql",
"host": "127.0.0.1",
"database": "test",
"user": "root",
"password": "warcraft"
}
}
models.json
{
"email": {
"options": {
"base": "Email"
},
"dataSource": "mail",
"public": false
},
"user": {
"options": {
"base": "User",
"relations": {
"accessTokens": {
"model": "accessToken",
"type": "hasMany",
"foreignKey": "userId"
}
}
},
"dataSource": "mysql",
"public": true
},
"accessToken": {
"options": {
"base": "AccessToken"
},
"dataSource": "mysql",
"public": true
},
"application": {
"options": {
"base": "Application"
},
"dataSource": "db",
"public": true
},
"acl": {
"options": {
"base": "ACL"
},
"dataSource": "db",
"public": false
},
"roleMapping": {
"options": {
"base": "RoleMapping"
},
"dataSource": "db",
"public": false
},
"role": {
"options": {
"base": "Role",
"relations": {
"principals": {
"type": "hasMany",
"model": "roleMapping",
"foreignKey": "roleId"
}
}
},
"dataSource": "db",
"public": false
},
"scope": {
"options": {
"base": "Scope"
},
"dataSource": "db",
"public": false
},
"push": {
"options": {
"base": "Push",
"plural": "push"
},
"dataSource": "push"
},
"installation": {
"options": {
"base": "Installation"
},
"dataSource": "db",
"public": true
},
"notification": {
"options": {
"base": "Notification"
},
"dataSource": "db",
"public": true
},
"product": {
"properties": {
"email": {
"type": "string"
},
"level": {
"type": "number"
},
"create": {
"type": "date"
},
"modified": {
"type": "date"
}
},
"public": true,
"dataSource": "db",
"plural": "products"
},
"account": {
"properties": {
"email": {
"type": "string"
},
"level": {
"type": "number"
},
"created": {
"type": "date"
},
"modified": {
"type": "date"
}
},
"public": true,
"dataSource": "mysql",
"plural": "accounts"
}
}
Console Output
{ username: 'timbo',
email: 'test#gmail.com',
password: '$2a$10$972DFwMOuOhKj5ThfbchC.ipcNaW27ccpHMRkW17uSLutaCHyZF0G',
realm: undefined,
emailVerified: undefined,
verificationToken: undefined,
credentials: [],
challenges: [],
status: undefined,
created: undefined,
lastUpdated: undefined,
id: undefined }
{ username: 'timbo2',
email: 'test2#gmail.com',
password: '$2a$10$1peSixaOIQq8umOzzEy86OQKxoPFU.Ax2/NWC1oLGjQHPp9oZdPDW',
realm: undefined,
emailVerified: undefined,
verificationToken: undefined,
credentials: [],
challenges: [],
status: undefined,
created: undefined,
lastUpdated: undefined,
id: undefined }
{ username: 'timbo3',
email: 'test3#gmail.com',
password: '$2a$10$X3fdV2dL6kjuj69Dqr.jMeVdqIMzveN7NnJP5TXag54b4tpzZ4LGW',
realm: undefined,
emailVerified: undefined,
verificationToken: undefined,
credentials: [],
challenges: [],
status: undefined,
created: undefined,
lastUpdated: undefined,
id: undefined }
This is the token: undefined
This is the token err: Error: ER_BAD_FIELD_ERROR: Unknown column 'ttl' in 'field list'
You have to attach User-related models to your datasource first:
loopback.User.attachTo(dataSource);
loopback.AccessToken.attachTo(dataSource);
loopback.Role.attachTo(dataSource);
loopback.ACL.attachTo(dataSource);
And define the relationship between User and AccessToken:
loopback.User.hasMany(loopback.AccessToken, {as: 'accessTokens'});
When creating test data, you should wait for User.create to finish before calling User.login. (Rember, Node.js is asynchronous.)
User.create(
{username: 'timbo', email: 'test#gmail.com', password: 'monkey123'},
function(err, user) {
// TODO: handle err != null
User.login(
{username: 'timbo', password: 'monkey123'},
function(err, accesstoken) {
console.log("This is the token: " + accesstoken);
});
});

Resources